capypad
0 day streak
go / intermediate
Snippet

Non-Blocking Channel Operations with Select

The 'select' statement lets a goroutine wait on multiple communication operations. Using a 'default' case allows for non-blocking sends and receives, executing immediately if no channel is ready.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
 
import "fmt"
 
func main() {
messages := make(chan string)
signals := make(chan bool)
 
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
 
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
}
Breakdown
1
select { ... }
Blocks until one of its cases can run, unless a default case is present.
2
case msg := <-messages:
Attempts to receive a value from the messages channel.
3
default:
Executed if no other case is ready, making the select operation non-blocking.