Middle+
How to syntactically prevent a reader from closing a channel?
sobes.tech AI
Answer from AI
In Go, you cannot directly prevent closing a channel because the close operator works with the channel, not its type. However, you can syntactically restrict access to closing the channel by passing the channel as read-only (<-chan T) in parts of the code where closing is not needed.
A channel in Go has three main types:
chan T— bidirectional channel (read and write)<-chan T— read-only channelchan<- T— write-only channel
Only the owner with a chan T can close the channel. If a function accepts <-chan T, it cannot close the channel because the close operator requires chan T.
Example:
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
}
// Only the owner with chan T can close the channel
}
func consumer(ch <-chan int) {
for v := range ch {
fmt.Println(v)
}
// Cannot call close(ch) here because ch is read-only
}
func main() {
ch := make(chan int)
go producer(ch)
consumer(ch)
}
Thus, to prevent the reader from closing the channel, pass it as <-chan T. Only the owner with chan T can close the channel.