Is there any case where I can use a channel without creating it with make, or should I always create it with make?
Does this also apply with maps and slices?
CodePudding user response:
Is there any case where I can use a channel without creating it with make
In general channels should be created with make
as per the spec:
A new, initialized channel value can be made using the built-in function make
However there are cases where a nil
channel is useful. The spec states that:
A nil channel is never ready for communication.
This can he helpful in some situations (see this answer for an example where a channel, awaitRequest
, is deliberately set to nil
). So, technically, you can "use a channel without creating it with make".
Does this also apply with maps and slices?
No - here are a few alternatives (playground):
var m map[int]int
fmt.Println(m[1]) // Note that you cannot add elements to a nil map
m1 := map[int]int{}
m1[1] = 2
m2 := map[int]int{1: 2}
fmt.Println(m2[0])
var s []int
fmt.Println(append(s, 1)) // Nil map is empty but you can append
s1 := []int{}
fmt.Println(append(s1, 2))
s2 := []int{1}
fmt.Println(s2[0])