Complete the code to wait on multiple channels using select.
select {
case msg := <-ch1:
fmt.Println("Received", msg)
case [1]:
fmt.Println("Timeout")
}The select statement waits on multiple channel operations. Using case <-time.After(time.Second) adds a timeout case.
Complete the select statement to handle messages from two channels.
select {
case msg1 := <-ch1:
fmt.Println("From ch1:", msg1)
case [1]:
fmt.Println("From ch2:", msg2)
}The select waits on both ch1 and ch2. The second case must receive from ch2.
Fix the error in the select statement to avoid blocking.
select {
case msg := <-ch1:
fmt.Println(msg)
[1]:
fmt.Println("No message received")
}The default case in select runs if no other case is ready, preventing blocking.
Fill both blanks to create a select that handles two channels and a default case.
select {
case msg := <-ch1:
fmt.Println("ch1:", msg)
case [1]:
fmt.Println("ch2:", msg)
default:
fmt.Println([2])
}The select listens on ch1 and ch2. The default prints a message when no channels are ready.
Fill all three blanks to create a select that handles two channels and a timeout.
select {
case msg := <-[1]:
fmt.Println("Received from first channel:", msg)
case msg := <-[2]:
fmt.Println("Received from second channel:", msg)
case <-[3]:
fmt.Println("Timeout occurred")
}time.After for timeout.The select waits on ch1, ch2, and a timeout channel from time.After.