Go Channels

Communication between goroutines using channels

Creating Channels

ch := make(chan int) # unbuffered channel
buffered := make(chan string, 10) # buffered channel (capacity 10)

Send and Receive

ch <- 42 # send value to channel
value := <-ch # receive from channel
value, ok := <-ch # receive with status check

Closing Channels

close(ch) # close channel
value, ok := <-ch # ok is false if closed
for value := range ch { # iterate until closed
    fmt.Println(value)
}

Select Statement

select { # wait on multiple channels
case msg := <-ch1: # receive from ch1
    fmt.Println(msg)
case ch2 <- value: # send to ch2
    fmt.Println("Sent")
default: # non-blocking
    fmt.Println("No communication")
}

Channel Direction

func send(ch chan<- int) { # send-only channel
    ch <- 42
}
func receive(ch <-chan int) { # receive-only channel
    value := <-ch
}