gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:44 26 4
gpt4 key购买 nike

我有以下运行正常的代码,我在 mStr 上循环并打印文件的值(value)

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

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


}
}

现在我需要的是提供范围过滤器,例如如果 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”)


}
}
}

虽然这可行,但它在代码中引入了一些 if else 分支以支持以下内容:

  1. 如果 mdl(它可以没有任何值)循环所有 mStr 值并打印到所有值。
  2. 如果 mdl 包含 value ,仅在 mod.Name == mdl[I] 时打印,否则不打印。

有没有一种更干净的方法可以在 Golang 中进行这种循环过滤?

最佳答案

检查您在函数中传递的 slice 的长度,如果 slice 为空,它将给出长度为零。

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

关于go - 在golang中的范围循环中过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51745139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com