Add select...default

This commit is contained in:
Sangeeth Sudheer 2024-04-28 16:14:14 +05:30
parent 00b427a3ab
commit c41662bff8
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 35 additions and 2 deletions

View File

@ -7,7 +7,8 @@ package main
// import "git.sangeeth.dev/gobyexample/goroutines" // import "git.sangeeth.dev/gobyexample/goroutines"
// import "git.sangeeth.dev/gobyexample/channels" // import "git.sangeeth.dev/gobyexample/channels"
// import "git.sangeeth.dev/gobyexample/cselect" // import "git.sangeeth.dev/gobyexample/cselect"
import "git.sangeeth.dev/gobyexample/timeouts" // import "git.sangeeth.dev/gobyexample/timeouts"
import "git.sangeeth.dev/gobyexample/selectdefault"
func main() { func main() {
// runes.Runes() // runes.Runes()
@ -17,5 +18,6 @@ func main() {
// goroutines.Goroutines() // goroutines.Goroutines()
// channels.Channels() // channels.Channels()
// cselect.Select() // cselect.Select()
timeouts.Timeouts() // timeouts.Timeouts()
selectdefault.SelectDefault()
} }

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