Add select...default

This commit is contained in:
2024-04-28 16:14:14 +05:30
parent 00b427a3ab
commit c41662bff8
2 changed files with 35 additions and 2 deletions

View 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")
}
}