我当然希望这是简单的事情。当我从 for 循环内的 if 语句中获取信息时,它不会被带到 for 循环外。我可以很好地从 if 语句中打印信息,然后再丢失它。我错过了什么吗?来自 Python 我以前从未经历过这种情况。
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
}
最佳答案
很可能是您覆盖了 neededinfo 变量
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)
}
关于go - for 循环的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665430/