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 :
mdl
is empty (it can be without any value)loop on all the mStr value and prints to all.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
}