Senior
What are the rules (axioms) for working with channels in Go?
sobes.tech AI
Answer from AI
In Go, channels are used for communication between goroutines and have several key rules (axioms):
- A channel is a typed queue that provides synchronization between sender and receiver.
- Sending to a channel blocks the goroutine if the channel buffer is full (for buffered channels) or if there is no receiver (for unbuffered channels).
- Receiving from a channel blocks the goroutine if the channel is empty.
- Closing a channel (
close(ch)) signals that no more sends will occur; receiving from a closed channel returns the zero value andfalseas the second value. - You cannot send to a closed channel — this will cause a panic.
- Channels can be used for data transfer and synchronization, but not for storing state.
Example:
ch := make(chan int, 1) // buffered channel
ch <- 42 // send
val := <-ch // receive
close(ch) // close the channel
v, ok := <-ch // ok == false if the channel is closed and empty
These rules ensure safe and predictable interaction between goroutines via channels.