英文:
Infinite 'for' loop in Go
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对Go语言还不熟悉,但我不希望在这样基本的问题上出现问题。
package main
import "fmt"
func main() {
s := make([]int, 0)
s = append(s, 1)
for len(s) != 0 {
j := len(s) - 1
top, s := s[j], s[:j]
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}
}
这段代码不会退出,它只会打印以下内容:
len(s) = 0
top = 1
s = []
len(s) = 0
top = 1
s = []
len(s) = ^C
我觉得这很令人惊讶,我做错了什么?从语法上来说,根据https://tour.golang.org/flowcontrol/3,一切似乎都没问题。
英文:
I'm new to Go, but I would expect not to have issues with something as basic as this.
package main
import "fmt"
func main() {
s := make([]int, 0)
s = append(s, 1)
for len(s) != 0 {
j := len(s) - 1
top, s := s[j], s[:j]
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}
}
This command doesn't exit. It just prints
len(s) = 0
top = 1
s = []
len(s) = 0
top = 1
s = []
len(s) = ^C
I find this stunning; what am I doing wrong? Syntactically, based on https://tour.golang.org/flowcontrol/3, everything seems OK.
答案1
得分: 6
当你使用:=
时,你声明了新的变量。在循环内部创建了一个与外部的s
无关的s
。改为赋值操作:
for len(s) != 0 {
j := len(s) - 1
var top int
top, s = s[j], s[:j]
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}
英文:
When you use :=
, you declare new variables. An s
is created inside the loop unrelated to the s
outside it. Assign instead:
<pre><code>for len(s) != 0 {
j := len(s) - 1
<b>var top int
top, s = s[j], s[:j]</b>
fmt.Printf("top = %+v\n", top)
fmt.Printf("s = %+v\n", s)
fmt.Printf("len(s) = %+v\n", len(s))
}</code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论