Add select...default
This commit is contained in:
31
selectdefault/selectdefault.go
Normal file
31
selectdefault/selectdefault.go
Normal file
@@ -0,0 +1,31 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user