在 golang 中的范围循环中过滤值



>我有以下代码运行正常,我在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分支来支持以下内容:

  1. 如果mdl为空(可以没有任何值(,则循环访问所有 mStr 值并打印到所有值。
  2. 如果 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
}

最新更新