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
Syntax
make(chan T[, size]) ch <- v v, ok := <-ch close(ch) select { case ... }
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
sync.WaitGroup· Wait for a group of goroutines to finish; WaitGroup.Go (Go 1.25+) starts a goroutine and tracks it in one call.context.WithTimeout and WithCancel· Derive a context that is cancelled after a timeout or on demand, to stop work and outbound calls that take too long.- Go Channels and select · tutorial