英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论