Nil, open and closed channel states
Nil, open and closed channel states
The zero value of a channel is nil. A direct send or receive on nil blocks indefinitely; closing a nil channel panics. Open channels communicate according to buffer space and peers. Closed channels permit receives but not sends. There is no general isClosed probe that makes a later send safe.
package main
import ( "fmt")
func main() { var ch chan int fmt.Println(ch == nil, len(ch), cap(ch)) ch = make(chan int, 1) fmt.Println(ch == nil, len(ch), cap(ch)) ch <- 6 close(ch) v, ok := <-ch fmt.Println(v, ok) v, ok = <-ch fmt.Println(v, ok)}len and cap are zero for nil and for an unbuffered channel. Neither reveals closure. A length check does not reserve a slot or value against competing goroutines.
Expected output:
true 0 0false 0 16 true0 falseGuard an optional channel
package main
import ( "fmt")
func optional(in <-chan int) (int, bool) { if in == nil { return 0, false } v, ok := <-in return v, ok}func main() { v, ok := optional(nil) fmt.Println(v, ok) ch := make(chan int, 1) ch <- 11 v, ok = optional(ch) fmt.Println(v, ok)}This function treats nil as absent. The two-result receive works in assignment: v, ok := <-in. Return the two variables explicitly; return <-in supplies only one result. It still blocks on an open empty non-nil channel. The next chapter introduces select for cancellation and nonblocking choices.
Expected output:
0 false11 trueTry it locally
Write receiveOptional for strings, returning empty,false for nil and otherwise a two-result receive. Test nil and a closed buffered channel containing "ok".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels 05: Nil, open and closed channel states
Check the lesson objective before moving on.
What does a direct receive from nil do?
Does len(ch)==0 prove closure?