gpt4 book ai didi

go - := 左侧非名称

转载 作者:行者123 更新时间:2023-12-01 22:33:00 24 4
gpt4 key购买 nike

我正在go中练习/尝试一些同步机制。 .

为什么最后一个for迭代无法分配缓冲 channel 保存的值 valchan进入mysl slice ?

错误是

./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 redeclarevariables 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]。这不符合“至少一个非空变量是新的”规则,因此编译器会提示。相反,您只想使用 = 运算符进行赋值。

关于go - := 左侧非名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com