Senior
What is the name of the approach in Go where you create a channel, close it, then read from it? What is the advantage of closing a channel over sending a value into it?
sobes.tech AI
Answer from AI
This approach is called "channel closing" in Go. When a channel is closed using close(ch), it signals to receivers that no more values will be sent.
Advantages of closing a channel instead of sending a special value:
- Receivers can use the
for val := range chconstruct to read all values until the channel is closed, simplifying the code. - Closing a channel allows distinguishing between the situation where the channel is empty but not closed, and the situation where no more data will be sent.
- There is no need to invent and check special placeholder values.
Example:
ch := make(chan int)
go func() {
defer close(ch)
for i := 0; i < 5; i++ {
ch <- i
}
}()
for val := range ch {
fmt.Println(val)
}
// After closing, the for loop will end automatically