>我有以下代码运行正常,我在mStr
上循环并打印 文件的值
func setFile(file io.Writer, mStr []*mod.M, mdl []string) {
for i, mod := range mStr {
fmt.Fprint(file, “app”)
fmt.Fprint(file, “app1”)
…
}
}
现在我需要的是提供一个范围过滤器, 例如,如果 mod,只需打印到文件。名称 =="应用程序"
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”)
…
}
}
}
虽然这可以工作,但它在代码中引入了一些if else
分支来支持以下内容:
- 如果
mdl
为空(可以没有任何值(,则循环访问所有 mStr 值并打印到所有值。 - 如果 mdl 包含值 ,则仅在
mod.Name == mdl[I]
不包含值时打印。
有没有更干净的方法来在 Golang 中对循环进行这种过滤?
检查你在函数中传递的切片的长度,如果切片为空,它将长度定为零。
if len(mdl) > 0 && mod.Name == mdl[i] {
fmt.Fprint(file, “app”)
fmt.Fprint(file, “app1”)
// code
}else{
// code
}