Infinite 'for' loop in Go

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

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>

huangapple
  • 本文由 发表于 2017年8月12日 16:00:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45647958.html
匿名

发表评论

匿名网友

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

确定