default and non-blocking
- Go course
- Intermediate
- Lesson 15/80
- 4 min
Learn non-blocking send and receive with default.
default and non-blocking
If you add default to select it runs when no case is ready, so select does not block. This enables non-blocking send and receive.
Non-blocking receive: select { case v := <-ch: ... default: }. If the channel has no data default runs. This is used for take-if-ready, else do other work.
Non-blocking pattern
The non-blocking pattern lets a goroutine check a channel and do other work if it is empty. This is an efficient alternative to busy waiting.
The pattern select { case x := <-ch: handle(x) default: doOther() } is common. If the channel has data it handles it; otherwise it moves on. This is the basis of event loops.
Practice Non-blocking select
Inside main, add a select { case ... default: ... } block and print non-blocking with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string)
select {
case m := <-ch:
fmt.Println(m)
default:
fmt.Println("non-blocking")
}
}Expected output
non-blocking
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the default case run?
- When no case is ready Correct answer
- Always
- When the first case is not ready
- Only on error
Explanation: when no case is ready. If even one case is ready default does not run.
2 default keyword
select {
case v := <-ch:
fmt.Println(v)
____:
fmt.Println("boş")
}
select {
case v := <-ch:
fmt.Println(v)
default:
fmt.Println("boş")
}
Explanation: else is for if/switch, not select.
3 Match default concepts
| Term | Meaning |
|---|---|
default |
When none ready |
non-blocking |
No wait |
case |
Channel op |
select |
Multi-wait |