:= 左侧的非名称

non-name on left side of :=

我正在 go.

中练习/试验一些同步机制

为什么最后一次 for 迭代无法将缓冲通道 valchan 保存的值分配给 mysl 切片?

错误是

./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
    }
}

您正在使用“短变量声明”语法。来自 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.

换句话说:您的代码尝试重新声明 mysl[i]。这不符合“至少有一个非空变量是新的”规则,所以编译器会抱怨。相反,您只想进行赋值 - 使用 = 运算符。