Initializing channels in Go
With most variables in Go we can declared them in a couple of different ways. Using the var keyword, initialize them as we declare them with the :=
operator; or using the new
or make
keywords.
Most variables can be declared with var
, which only reserves storage for a named variable. If no assignment accompanies the statement, the variable is set to it’s zero value. Using var
to declare a channel crates a nil channel. The underlying header is created, but there is no backing data structure. If we use the make
keyword we reserve storage, initializes memory, and create the backing header for the specified type.
Declaring variables using var
reserves storage and initializes with a Type’s zero value. Channels work this way too, they are initalized to a nil channel. Which we could use if if we have an existing channel we want to assign, or have a function that creates a channel we want to assign to our named channel. Sending or receiving on a channel does not initialize it.
In most cases we will want to use make
when creating channels to use ourselves.
View on the golang playground