Blocking goroutine forever

Michał Łowicki
golangspec
2 min readNov 5, 2016

--

Certain operations using channels can block the whole goroutine forever. Let’s see a couple of maybe less practical examples which allow to learn some nuances about the language.

The most concise way is probably select {}. If there is no default clause, select statement blocks till at least one channel is ready for communication. Since there are no channels involved, statement blocks forever.

Reading from channel to which it’s guaranteed nothing will be ever sent causes a deadlock: <-make(chan int).

Other options are variants of interacting with nil channel. It’s a zero value for not initialized channel. Zero value for pointers, functions, interfaces, maps, slices or channels is nil. Sending to or receiving from nil channel, blocks forever:

var ch chan int
<-ch
ch<-1

Range expression can be applied to channel. It iterates through values sent over such channel. If it’s a nil channel then range expression blocks forever:

var ch chan int
for range ch {
}

--

--

Michał Łowicki
golangspec

Software engineer at Datadog, previously at Facebook and Opera, never satisfied.