Channels
A channel is a typed pipe between goroutines: chan T. Send ch <- v and receive v := <-ch synchronize the two sides. Channels move values and, when unbuffered, also act as a handshake.
Detailed Explanation
You have a producer that reads lines and a consumer that writes them. A channel is the queue the language provides. ch := make(chan string) is unbuffered: the send waits until a receive happens. make(chan string, 8) is buffered: send waits only when the buffer is full.
Zero value is nil. A nil channel blocks forever on send and receive. Closing a nil channel panics. make before use, the same as a map.
Close is a signal, not a destructor. close(ch) says "no more sends." Receivers get remaining buffered values, then zero T and ok == false. Send on a closed channel panics. Only the sending side closes. Do not close if there are multiple senders unless you have a separate counter that decides who is last.
Range. for v := range ch receives until the channel is closed and drained. If nobody closes, the loop blocks forever.
Copy of the value. A send copies v into the channel. Large structs should be sent as pointers if you mean to share, and as values if you mean to hand off a snapshot.
What it costs. Each send/receive is a synchronization. Unbuffered channels are a clean signal. Buffered channels decouple bursts. A channel is not a replacement for a mutex protecting a struct: if two goroutines must update many fields together, lock, or pass the whole struct through a channel so only one owner exists at a time.
Code Examples
package main
import "fmt"
func main() {
ch := make(chan string)
go func() { ch <- "ping" }()
fmt.Println(<-ch)
}func produce(n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < n; i++ {
out <- i
}
}()
return out
}
func main2() {
for v := range produce(3) {
fmt.Println(v)
}
}Common Gotchas
Send or close on a closed channel panics
close from one sender, once.
Receive from a nil channel blocks forever
initialize with `make`.
Forgetting `close` leaves `range` blocked
the receiving goroutine leaks.
`v, ok := <-ch` distinguishes a zero value from a closed channel
`v, ok := <-ch` distinguishes a zero value from a closed channel