可以不使用make函数创建通道吗?

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

Can I create channel without using the make function?

问题

以下是翻译好的内容:

以下代码可以正常工作:

func main() {
    c := make(chan string)
    go subRountine(c)
    fmt.Println(<-c)
}

func subRountine(c chan string) {
    c <- "hello"
}

是否有其他方法可以创建一个通道而不使用 make 函数?像这样的方式,但是这个示例不起作用:

func main() {
    var c chan string
    go subRountine(c)
    fmt.Println(<-c)
}

func subRountine(c chan string) {
    c <- "hello"
}
英文:

The following code works okay

func main() {
	c := make(chan string)
	go subRountine(c)
	fmt.Println(&lt;-c)
}

func subRountine(c chan string) {
	c &lt;- &quot;hello&quot;
}

Is there any other method to create a channel without the make function?
Something like this but this sample does not work

func main() {
	var c chan string
	go subRountine(c)
	fmt.Println(&lt;-c)
}

func subRountine(c chan string) {
	c &lt;- &quot;hello&quot;
}

答案1

得分: 3

TL;DR

没有绕过的方法:你必须使用make函数。

更多细节

var c chan string

仅仅声明了一个通道变量,但没有初始化通道!这是有问题的,因为,正如语言规范所述

> 未初始化的通道的值是nil

并且

> nil通道永远不会准备好进行通信。

换句话说,向一个nil通道发送和/或接收操作是阻塞的。虽然nil通道值_可以_有用,但如果你想在通道上执行_通道通信_(发送或接收),你必须在某个阶段初始化通道。

正如mkopriva在他的评论中所写的,Go只提供了一种初始化通道的方法:

> 可以使用内置函数make来创建一个新的、初始化的通道值,该函数接受通道类型和一个可选的_容量_作为参数:
>
> make(chan int, 100)

英文:

TL;DR

No way around it: you must use make.

More details

var c chan string

merely declares a channel variable, but without initialising the channel! This is problematic because, as the language spec puts it

> The value of an uninitialized channel is nil.

and

> A nil channel is never ready for communication.

In other words, sending and/or receiving to a nil channel is blocking. Although nil channel values can be useful, you must initialise a channel at some stage if you ever want to perform channel communications (send or receive) on it.

As mkopriva writes in his comment, Go provides only one way of initialising a channel:

> A new, initialized channel value can be made using the built-in function make, which takes the channel type and an optional capacity as arguments:
>
> make(chan int, 100)

答案2

得分: 1

不!使用var声明一个通道与创建一个通道是不同的。你应该使用make来创建通道:

  var c chan string
  c = make(chan string)

不同之处在于现在你可以在底层作用域中创建c并在其外部使用。

请注意,你不应该在等号前面加上冒号。

英文:

No! Declaring a channel with var is different from creating it. Then you should create by make:

  var c chan string
  c = make(chan string)

With the difference that now you can make c in underlying scops and use it outside of them.

<i>Note that you shouldn't put colons before the equals sign in this way.</i>

huangapple
  • 本文由 发表于 2022年3月26日 17:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/71626679.html
匿名

发表评论

匿名网友

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

确定