Channels Cheatsheet
Goroutines
- Spawn:
go funcName()
- Anonymous:
go func() { ... }()
Channels
- Create (Unbuffered):
ch := make(chan int)
- Create (Buffered):
ch := make(chan int, 100)
- Send:
ch <- value
- Receive:
v := <-ch
- Signalling:
ch := make(chan struct{})
Closing & Safety
- Close:
close(ch)
- Check:
v, ok := <-ch (ok is false if empty and closed)
- Rules:
- Sending to closed channel → Panic
- Closing already closed channel → Panic
- Receiving from closed channel → Zero value
Iteration & Selection
- Range:
for v := range ch { ... } (exits when closed)
- Select:
select {
case v := <-ch1:
case ch2 <- 42:
default: // Makes select non-blocking
}
Time & Direction
- Ticker:
time.Tick(1 * time.Second)
- Timeout:
time.After(5 * time.Second)
- Read-Only:
<-chan T
- Write-Only:
chan<- T
Critical Notes
- Nil channels block forever (send or receive).
- Slices and maps are reference types; channels are too.
- If
main exits, all other goroutines die immediately.