Common Channel Mistakes and Deadlocks in Go

Prevent Go deadlocks by ensuring channel operations have matching sends and receives or using buffered channels.

Deadlocks in Go occur when goroutines block indefinitely waiting for channel operations that never complete, often due to unbuffered channels or missing sends/receives. Use buffered channels or ensure every send has a corresponding receive to prevent blocking.

// Deadlock: Unbuffered channel blocks if no receiver is ready
ch := make(chan int)
ch <- 1 // Blocks forever if no other goroutine reads from ch

// Fix: Use a buffered channel or add a receiver
ch := make(chan int, 1)
ch <- 1 // Non-blocking with buffer size 1

// Or ensure a receiver exists
ch := make(chan int)
go func() { <-ch }() // Receiver ready
ch <- 1 // Now safe