创建频道时新建 vs 制作

new vs make when creating channel

在 Go 中,我阅读了文档并了解 makenew

之间的基本区别

我阅读了文档,主要是使用数组的示例。创建数组时,我了解 newmake。但是我不明白创建频道时的区别:

c1 := new(chan string)
c2 := make(chan string)

除了 c1 的类型为 (chan*) 而 c2 的类型为 chan 之外,真正的区别是什么。

谢谢

new 的行为在 Allocation with new 中有解释。

It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it.

在这种情况下 new(chan string) returns 指向类型为 chan string 的零值的指针,即 nil 通道。以下程序在尝试从 nil 通道读取时死锁。

package main

import (
    "fmt"
)

func main() {
    c1 := new(chan string)
    fmt.Println(*c1)
    go func() {
        *c1 <- "s"
    }()
    fmt.Println(<-*c1)
}

使用 make(chan string) 你会得到一个实际可用的频道,而不是频道类型的零值。

package main

import (
    "fmt"
)

func main() {
    c2 := make(chan string)
    fmt.Println(c2)
    go func() {
        c2 <- "s"
    }()
    fmt.Println(<-c2)
}