Go 1.27 reference · Concurrency

Go chan, select and close Keyword

Send values between goroutines with channels, wait on several with select, and close a channel to end range loops.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

make(chan T[, size])   ch <- v   v, ok := <-ch   close(ch)   select { case ... }

Parameters

ParameterDescription
unbuffered / buffered Send blocks until received / until the buffer is full.
close(ch) No more values; range loops end.
v, ok := <-ch ok is false once closed and empty.
select Wait on several channel operations.

Examples

Example 1
package main

import "fmt"

func main() {
	jobs := make(chan int)
	results := make(chan int)
	go func() {
		for j := range jobs {
			results <- j * 10
		}
		close(results)
	}()
	go func() {
		for i := 1; i <= 3; i++ {
			jobs <- i
		}
		close(jobs)
	}()
	for r := range results {
		fmt.Println(r)
	}
}

Output

10
20
30

Run this on your computer — see “Get Started” for setup.

select with a timeout, and closed channels
package main

import (
	"fmt"
	"time"
)

func main() {
	fast := make(chan string, 1)
	fast <- "cache hit"
	select {
	case v := <-fast:
		fmt.Println(v)
	case <-time.After(time.Second):
		fmt.Println("timeout")
	}
	ch := make(chan int)
	close(ch)
	v, ok := <-ch
	fmt.Println(v, ok)
}

Output

cache hit
0 false

Run this on your computer — see “Get Started” for setup.

Was this page helpful?