I'm trying to understand a simple code of Golang routines:
package main
import (
"fmt"
"time"
)
func sleep(seconds int, endSignal chan<- bool) {
time.Sleep(time.Duration(seconds) * time.Second)
endSignal <- true
}
func main() {
endSignal := make(chan bool, 1)
go sleep(3, endSignal)
var end bool
for !end {
select {
case end = <-endSignal:
fmt.Println("The end!")
case <-time.After(5 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
}
}
}
That's fine, but Why I cannot use a simple default in this "select" block? Something like this:
for !end {
select {
case end = <-endSignal:
fmt.Println("The end.")
case <-time.After(4 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
default:
fmt.Println("No end signal received.")
}
}
It gets this output:
❯ go run goroutines-timeout.go
No end signal received!
No end signal received!
No end signal received!
No end signal received!
...
The end!
And I can't understand why.