-1

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107
  • 1
    @Flimzy I have searched that post before but I cannot map that concept to "channel". So I asked this question. – Trần Kim Dự Mar 01 '18 at 18:14
  • That question directly and clearly addresses the question of channels. If you didn't "map" that concept, it means you didn't read the answers. – Jonathan Hall Mar 02 '18 at 08:05

1 Answers1

5

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)
}
dtolnay
  • 9,621
  • 5
  • 41
  • 62