在 := 的左侧出现了非名称。

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

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 (
	&quot;sync&quot;
)

const NUM_ROUTINES = 2

func sendValue(c chan string) {
	c &lt;- &quot;HelloWorld&quot;
}

func main() {
	valchan := make(chan string, NUM_ROUTINES)
	var wg sync.WaitGroup
	wg.Add(NUM_ROUTINES)

	for i := 0; i &lt; NUM_ROUTINES; i++ {
		go func() {
			sendValue(valchan)
			wg.Done()
		}()
	}
	wg.Wait()

	mysl := make([]string, 2, 2)
	for i := 0; i &lt; NUM_ROUTINES; i++ {
		mysl[i] := &lt;-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.

huangapple
  • 本文由 发表于 2019年11月3日 21:18:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/58680519.html
匿名

发表评论

匿名网友

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

确定