英文:
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 < 10; i++, k++ {
for j := 0; j < 10; j++ {
if k == 10 {
fmt.Println("Value of k is:", 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
你需要同时初始化k
和i
:for 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,所以你的消息不会被打印出来。你同时增加了i
和k
,而外层循环停在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 < 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("Value of k is:", 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 < 10
(and thus k < 10
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论