Tutorial by Examples

When reading multiple values from a channel, using range is a common pattern: func foo() chan int { ch := make(chan int) go func() { ch <- 1 ch <- 2 ch <- 3 close(ch) }() return ch } func main() { for n := r...
Channels are often used to implement timeouts. func main() { // Create a buffered channel to prevent a goroutine leak. The buffer // ensures that the goroutine below can eventually terminate, even if // the timeout is met. Without the buffer, the send on the channel // blocks fo...
Imagine a goroutine with a two step process, where the main thread needs to do some work between each step: func main() { ch := make(chan struct{}) go func() { // Wait for main thread's signal to begin step one <-ch // Perform work time.Sle...
func bufferedUnbufferedExample(buffered bool) { // We'll declare the channel, and we'll make it buffered or // unbuffered depending on the parameter `buffered` passed // to this function. var ch chan int if buffered { ch = make(chan int, 3) } else { ch...
By default communication over the channcels is sync; when you send some value there must be a receiver. Otherwise you will get fatal error: all goroutines are asleep - deadlock! as follows: package main import "fmt" func main() { msg := make(chan string) msg <- "He...
A common technique for using channels is to create some number of workers (or consumers) to read from the channel. Using a sync.WaitGroup is an easy way to wait for those workers to finish running. package main import ( "fmt" "sync" "time" ) func ...

Page 1 of 1