Junior — Middle
How should software behave if you try to read data from a channel that was set to nil?
sobes.tech AI
Answer from AI
In Go, if you try to read data from a channel that is nil, the read operation will block indefinitely, meaning the program will hang on this operation.
This is because a nil channel is uninitialized and cannot send or receive data. Therefore, reading from a nil channel will not complete until an external event occurs (for example, context cancellation or program termination).
Example:
var ch chan int // ch == nil
func main() {
fmt.Println("Attempting to read from a nil channel")
val := <-ch // the program will block here forever
fmt.Println(val) // this line will not execute
}
To avoid blocking, you need to ensure that the channel is not nil before reading.