Junior — Middle
What possible states can channels occupy during their use or operation?
sobes.tech AI
Answer from AI
Channels in Go can be in the following states:
- Open: the channel is available for sending and receiving data.
- Closed: the channel is closed using the
close()function. After closing, data cannot be sent, but already sent values can still be received until the channel is empty. - Blocked: a goroutine trying to send or receive data may be blocked if the channel is full (for buffered channels) or empty (for unbuffered channels).
Example:
ch := make(chan int, 1) // buffered channel
ch <- 1 // send value
close(ch) // close channel
v, ok := <-ch // receive value, ok == true
v2, ok2 := <-ch // channel is empty, ok2 == false
Thus, the channel's state affects the behavior of send and receive operations.