在Golang的范围循环中过滤值

I’ve the following code which runs ok, Im looping on the mStr and printing Value to a file

func setFile(file io.Writer, mStr []*mod.M, mdl []string) {

    for i, mod := range mStr {
            fmt.Fprint(file, “app”)
            fmt.Fprint(file, “app1”)
                        …

    }
}

Now what I need is to provide a filter on the range , e.g. just prints to file if mod.Name ==“app”

func setFile(file io.Writer, mStr []*mod.M, mdl []string) {

    for i, mod := range mStr {

    if mod.Name == mdl[i] {
            fmt.Fprint(file, “app”)
            fmt.Fprint(file, “app1”)
                        …

    }
  }
}

While this could work, it introduce a few if else forks in the code to support the following :

  1. If mdl is empty (it can be without any value)loop on all the mStr value and prints to all.
  2. If mdl contain value , prints only when the mod.Name == mdl[I] otherwise don’t.

Is there a cleaner way to do this kind of filtering on loop in Golang?

Check for length of slice that you are passing in the function if the slice is empty it will give the length as zero.

if len(mdl) > 0 && mod.Name == mdl[i] {
        fmt.Fprint(file, “app”)
        fmt.Fprint(file, “app1”)
        // code
}else{
     // code
}