Middle+
How to close a reader channel in Go? What happens if you write to a closed channel?
sobes.tech AI
Answer from AI
In Go, a channel is closed using the built-in function close(channel). Closing a channel signals to all receivers that no more values will be sent.
If a reader tries to read from a closed channel, they will receive the zero value of the channel's type and a flag ok == false, which allows for proper handling of the end of data.
Attempting to write to a closed channel will cause a panic (panic), as writing to a closed channel is forbidden and will lead to an abrupt termination of the program.
Example:
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // closing the channel
}()
for val := range ch { // read while the channel is open
fmt.Println(val)
}
// ch <- 10 // will cause panic: send on closed channel