I though channels in Go were simple.
Until I started encountering deadlocks in the scrapt scripts I was writing in my sandbox repository.
The problem: unbuffered channels block the goroutine that uses them.
Go
ch := make(chan int) ch <- 42 // deadlocks if no one is readingIf I send first and no reader exists yet, my whole main just freezes. Nothing after it runs.
Go even kills the program with deadlock.
That felt kinda backwards for me. Why should the order matter?
But I came to terms with the fix which was also a bit of a worry at the time: you have to guarantee a reader is ready before you send.
Usually by starting a go routine first:
Go
go func(){ <-ch }() // reader waiting
ch <- 42 // now safe to sendIf both send and receive are in goroutines, order doesn't matter.
They'll just wait for each other.
Now I see why channels are a synchronization point.
If you forget the other side, your code just... stops.