Channels
A channel passes a value and the fact "I am finished". The sender closes it. The reader leaves range by itself.
A channel is a typed queue and synchronization at the same time.
ch := make(chan int) // буфер 0, встреча обязательна
buf := make(chan int, 4) // до четырёх значений без встречи
A send on a channel with no buffer waits until someone receives the value. That is convenient for the signal "the work is done" and harmful if there is no receiving goroutine: the sender blocks forever. A buffer smooths a burst, but it does not replace waiting. A full buffer blocks the sender too.
Closing with close(ch) says: there will be no more values. The one who sends is the one who closes. A receiver that closes someone else's channel easily causes a panic "send on closed channel" if the sender is still alive. Closing twice panics too.
for v := range ch reads until the channel is closed. After closing, a read immediately returns the zero value and ok == false:
v, ok := <-ch
The first read takes the value. The next one, after closing, is already empty. You cannot tell "they sent a zero" from "the channel is closed" without ok.
A direction in the type makes the contract shorter: chan<- int only sends, <-chan int only receives. The function Drain(ch <-chan int) promises that it will not close the channel and will not write to it.
Do not use a channel as a queue "just in case" where a slice and one result are enough. A channel is needed when the producer and the consumer live at the same time.
Practice
Who closes
Who should close a channel of jobs if several goroutines read from it?
- Any receiver, whoever is free first
- The sender, when the values are finished
- The garbage collector. Closing by hand is not needed
- main, even if the sender is still working
A sum from a channel
Write
Drain(ch <-chan int) int. Read the channel until it is closed and return the sum of the values. An already closed empty channel gives 0. The channel will be closed from the outside. You do not close it yourself.The second read
The value 7 was put into a channel and the channel was closed. The first read took 7. What do the value and
okreturn on the second readv, ok := <-ch? Write the number andtrueorfalse, separated by a space.