Junior — Middle
What are the consequences of not closing the channel after use?
sobes.tech AI
Answer from AI
If you do not close a channel in Go after its use is complete, the following consequences may occur:
- Goroutine blocking: If other goroutines are waiting for data from the channel and it is not closed, they may wait indefinitely as they will not receive a signal that data transmission has ended.
- Resource leaks: Although the channel itself does not require explicit memory release, an unclosed channel can lead to logical errors and program hangs.
- Inability to correctly handle the end of transmission: A closed channel allows using
for rangeor checkingokto determine that data has finished. Without closing, this is impossible.
Example of proper channel closing:
ch := make(chan int)
go func() {
defer close(ch)
for i := 0; i < 5; i++ {
ch <- i
}
}()
for v := range ch {
fmt.Println(v)
}
Here, the channel is closed after sending all values, allowing the range loop to terminate correctly.