创建频道时,新vs制作[重复]

This question already has an answer here:

In Go, I read document and understand basic differences between make and new

  • new: return a pointer (*T) and zeros value it points to
  • make: return type T

I read document and mostly example using array. I understand new vs make when creating array. But I don't understand differences when creating channel:

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

What is real differences except that c1 has type (chan*) and c2 has type chan.

Thanks

</div>

The behavior of new is explained in 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.

In this case new(chan string) returns a pointer to a zero value of type chan string, which is the nil channel. The following program deadlock as it tries to read from a nil channel.

package main

import (
    "fmt"
)

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

With make(chan string) you get an actual usable channel, not a zero value of channel type.

package main

import (
    "fmt"
)

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