gobyexample/selectdefault/selectdefault.go

32 lines
834 B
Go

package selectdefault
import "fmt"
func SelectDefault() {
msgs := make(chan string)
signals := make(chan string)
select {
case val := <-msgs:
fmt.Println("Received", val)
default:
fmt.Println("`default` can be used to prevent blocking when there's nothing to receive from a channel")
}
select {
case msgs <- "hello":
fmt.Println("Sent hello")
default:
fmt.Println("`default` can be used to prevent blocking when we send something to an unbuffered channel but there's nobody to receive")
}
select {
case val := <-msgs:
fmt.Println("Received something from msgs", val)
case val := <-signals:
fmt.Println("Received something from signals", val)
default:
fmt.Println("`default` can be used to prevent blocking when there's nothing to receive or if its not possible to send across multiple channels")
}
}