Go by Example

Channels

Send typed values between goroutines and synchronize their work with channels.

A channel carries values between goroutines. An unbuffered send waits until a receiver is ready, so sending and receiving also synchronize the two goroutines.

Create a channel with make(chan T). Send with ch <- value and receive with value := <-ch.

package main
 
import "fmt"
 
func main() {
    ch := make(chan int)
    go func() { ch <- 42 }()
    value := <-ch
    fmt.Println(value)
}

In production

Only the sender that owns a channel should close it, after all sends are complete. Sending on a closed channel panics. Receiving from a closed and drained channel returns the zero value immediately, so use the comma-ok form when that distinction matters.

Enjoyed this? Get more software craft delivered to your inbox.