Sobes.tech
Junior

What does the default construct do in a select statement?

sobes.tech AI

Answer from AI

The default construct in a select statement executes a block of code if none of the other channels listed in the select are ready for reading or writing at the moment. This prevents the goroutine from blocking.

Example:

// Example with default
select {
case msg1 := <-channel1:
	fmt.Println("Received message 1:", msg1)
case msg2 := <-channel2:
	fmt.Println("Received message 2:", msg2)
default:
	fmt.Println("Channels are not ready, default executed")
}

Using default makes the select operation non-blocking. If default is absent, select will wait until one of the channels is ready.