英文:
non-name on left side of :=
问题
我正在练习/尝试使用go
中的同步机制。
为什么最后一个for
循环迭代无法将缓冲通道valchan
中保存的值分配给mysl
切片?
错误信息为
> ./myprog.go:28:7: 在:=的左侧,非名称 mysl[i]
package main
import (
"sync"
)
const NUM_ROUTINES = 2
func sendValue(c chan string) {
c <- "HelloWorld"
}
func main() {
valchan := make(chan string, NUM_ROUTINES)
var wg sync.WaitGroup
wg.Add(NUM_ROUTINES)
for i := 0; i < NUM_ROUTINES; i++ {
go func() {
sendValue(valchan)
wg.Done()
}()
}
wg.Wait()
mysl := make([]string, 2, 2)
for i := 0; i < NUM_ROUTINES; i++ {
mysl[i] := <-valchan
}
}
英文:
I am practicing / experimenting a bit with synchronisation mechanics in go
.
Why does the last for
iteration fail to assign the values held by the buffered channel valchan
into mysl
slice?
The error is
> ./myprog.go:28:7: non-name mysl[i] on left side of :=
package main
import (
"sync"
)
const NUM_ROUTINES = 2
func sendValue(c chan string) {
c <- "HelloWorld"
}
func main() {
valchan := make(chan string, NUM_ROUTINES)
var wg sync.WaitGroup
wg.Add(NUM_ROUTINES)
for i := 0; i < NUM_ROUTINES; i++ {
go func() {
sendValue(valchan)
wg.Done()
}()
}
wg.Wait()
mysl := make([]string, 2, 2)
for i := 0; i < NUM_ROUTINES; i++ {
mysl[i] := <-valchan
}
}
答案1
得分: 5
你正在使用“短变量声明”语法。根据语言规范:
它是一个带有初始化表达式但没有类型的常规变量声明的简写形式
...
与常规变量声明不同,短变量声明可以重新声明变量,前提是它们最初在同一块中(或者如果该块是函数体,则在参数列表中)以相同的类型进行了声明,并且至少有一个非空白变量是新的。
换句话说,你的代码尝试重新声明 mysl[i]
。这不符合“至少有一个非空白变量是新的”规则,所以编译器会报错。相反,你应该只进行赋值操作 - 使用 =
运算符。
英文:
You're using the "short variable declaration" syntax. From the language specification:
> It is shorthand for a regular variable declaration with initializer expressions but no types
>
> ...
>
> Unlike regular variable declarations, a short variable declaration may redeclare
variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new.
Put differently: your code tries redeclaring mysl[i]
. This does not conform to the "at least one of the non-blank variables is new" rule, so the compiler complains. Instead, you'll want to do only an assignment - using the =
operator.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论