获取语法错误:意外的逗号,期望 {

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

Getting syntax error: unexpected comma, expecting {

问题

我在尝试使用golang的break和continue,我写了以下代码:

func main() {
    for k, i := 0, 0; i < 10; i++, k++ {
        for j := 0; j < 10; j++ {
            if k == 10 {
                fmt.Println("Value of k is:", k)
                break
            }
        }
    }
}

在第一个for循环的行上,我遇到了以下语法错误:

语法错误:意外的逗号,期望 {

我不知道正确的语法应该是什么样的。

英文:

I was trying for, break and continue in golang and I did this...

func main() {
	for k, i := 0, 0; i &lt; 10; i++, k++ {
		for j := 0; j &lt; 10; j++ {
			if k == 10 {
				fmt.Println(&quot;Value of k is:&quot;, k)
				break
			}
		}
	}
}

I am getting this syntax error on line of the 1st for:

> syntax error: unexpected comma, expecting {

I don't know, how the correct syntax should be instead.

答案1

得分: 12

你需要同时初始化kifor k, i := 0, 0;

此外,你不能使用i++, k++,而是需要使用i, k = i+1, k+1

参考Effective Go中的说明:

最后,Go语言没有逗号运算符,++--是语句而不是表达式。因此,如果你想在for循环中使用多个变量,你应该使用并行赋值(尽管这样就不能使用++--)。

// 反转一个切片

for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] }

func main() {
	for k, i := 0, 0; i < 10;  i, k = i+1, k+1 {
		for j := 0; j < 10; j++ {
			if k == 10 {
				fmt.Println("k的值为:", k)
				break
			}
		}
	}
}

注意,这样k永远不会达到10,所以你的消息不会被打印出来。你同时增加了ik,而外层循环停在i < 10(因此也是k < 10)。

英文:

You need to initialize both k and i: for k, i := 0, 0;

Additionally you can't do: i++, k++. Instead you have to do i, k = i+1, k+1

See this reference in Effective Go:

> Finally, Go has no comma operator and ++ and -- are statements not
> expressions. Thus if you want to run multiple variables in a for you
> should use parallel assignment (although that precludes ++ and --).
>
> // Reverse a

> for i, j := 0, len(a)-1; i &lt; j; i, j = i+1, j-1 {
&gt; a[i], a[j] = a[j], a[i] }

func main() {
	for k, i := 0, 0; i &lt; 10;  i, k = i+1, k+1 {
		for j := 0; j &lt; 10; j++ {
			if k == 10 {
				fmt.Println(&quot;Value of k is:&quot;, k)
				break
			}
		}
	}
}

Note also that k never reaches 10 like this, so your message won't print. You are incrementing i & k at the same time and the outer loop stops at i &lt; 10 (and thus k &lt; 10).

huangapple
  • 本文由 发表于 2015年6月21日 18:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/30963511.html
匿名

发表评论

匿名网友

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

确定