Tell me about the equivalent of the default operator in the select statement.
sobes.tech AI
Answer from AI
The default operator in a select block allows executing an action if none of the channels specified in the case branches are ready for receiving or sending data without blocking.
It is used to implement non-blocking read or write from/to channels, as well as to set timeouts.
Example of using default for non-blocking read from a channel:
package main
import "fmt"
func main() {
ch := make(chan int, 1)
select {
case val := <-ch:
fmt.Println("Received value:", val)
default:
fmt.Println("Channel is empty, no data available.")
}
}
In this example, if the channel ch is empty, execution will go to the default branch, and the program will not wait for data.
Example of using default for non-blocking write to a channel:
package main
import "fmt"
func main() {
ch := make(chan int, 1)
data := 10
select {
case ch <- data:
fmt.Println("Data successfully sent to the channel.")
default:
fmt.Println("Channel is full, cannot send data without blocking.")
}
}
Here, if the channel ch is full, the attempt to write in the case ch <- data: branch will block. default allows avoiding this and performing an alternative action.
default is optional. If it is absent and none of the channels are ready, the select block will block the goroutine until one of the channels becomes ready.