for循环的行为出现了意外的结果。

huangapple go评论93阅读模式
英文:

Unexpected behavior from for loop

问题

我希望这是一个简单的问题。当我从一个for循环内部的if语句中获取信息时,它不会传递到for循环外部。我可以正常地从if语句中打印信息,但之后就会丢失。我是不是漏掉了什么?作为一个来自Python的人,我以前从未遇到过这种情况。

func main() {
    var neededinfo string
    for _, slice := range info_slices {
        // 从slice中获取信息
        if strings.Contains(slice, "indicator") {
            neededinfo := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = neededinfo[1:len(neededinfo)-2]
            fmt.Println(neededinfo) // 返回我的信息
        }
    }
    fmt.Println(neededinfo) // 什么都不返回
}
英文:

I sure hope this is something simple. When I grab information from within an if statement that is inside of a for loop it is not carried to outside of the for loop. I can print the information from within the if statement just fine and then lose it afterwards. Am I missing something? Coming from Python I have never experienced this before.

func main() {
    var neededinfo string
    for _, slice := range info_slices {
        // Get information out of slices
        if strings.Contains(slice, "indicator ") {
            neededinfo := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = neededinfo[1:len(neededinfo)-2]
            fmt.Println(neededinfo) // Returns my information
        }
    }
    fmt.Println(neededinfo) // Returns nothing
}

答案1

得分: 2

最有可能的情况是你正在覆盖 neededinfo 变量。

func main() {
    var neededinfo []string
    for _, slice := range info_slices {
        // 从切片中获取信息
        if strings.Contains(slice, "indicator ") {
            response := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = append(neededinfo, response[1:len(response)-2])
        }
    }
    fmt.Println(neededinfo) 
}

请注意,这只是代码的翻译,我无法提供关于代码的任何解释或建议。

英文:

Most likely is the fact that you are overwriting the neededinfo variable

func main() {
    var neededinfo []string
    for _, slice := range info_slices {
        // Get information out of slices
        if strings.Contains(slice, "indicator ") {
            response := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = append(neededinfo, response[1:len(response)-2]
        }
    }
    fmt.Println(neededinfo) 
}

huangapple
  • 本文由 发表于 2014年7月10日 07:47:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/24665430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定