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

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

Unexpected behavior from for loop

问题

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

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

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.

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

答案1

得分: 2

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

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

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

英文:

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

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

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:

确定