Consider this Go program that uses select to wait on multiple channels. What will it print?
package main import ( "fmt" "time" ) func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(100 * time.Millisecond) ch1 <- "from ch1" }() go func() { time.Sleep(50 * time.Millisecond) ch2 <- "from ch2" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) } }
Think about which goroutine sends data first and how select picks the ready channel.
The select statement waits for the first channel that is ready to send or receive. Since ch2 sends after 50ms and ch1 after 100ms, select receives from ch2 first and prints "from ch2".
Which of the following best explains why the select statement is needed in Go?
Think about how Go handles multiple channel communications at the same time.
select lets a goroutine wait on multiple channel operations and proceed with whichever is ready first. This is essential for handling multiple concurrent events without blocking on just one channel.
Examine this Go code snippet using select. What error will it produce when run?
package main func main() { ch := make(chan int) select { case val := <-ch: println(val) } }
Think about what happens when a goroutine waits to receive from a channel with no sender.
The program deadlocks because the main goroutine waits to receive from ch, but no other goroutine sends data. Since ch is unbuffered and no sender exists, the program blocks forever and causes a deadlock.
What will this Go program print?
package main import ( "fmt" "time" ) func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { ch1 <- "hello" }() go func() { ch2 <- "world" }() select { case msg := <-ch1: fmt.Println(msg) case msg := <-ch2: fmt.Println(msg) default: fmt.Println("no message received") } }
Consider the timing of goroutines and the default case in select.
The select statement checks channels immediately. Since the goroutines sending to ch1 and ch2 run asynchronously and may not have sent yet, the default case executes immediately, printing "no message received".
Which statement best describes how Go's select improves concurrency control compared to blocking on a single channel?
Think about how waiting on multiple channels helps a goroutine stay active.
select lets a goroutine wait on many channels and proceed with whichever is ready first. This avoids blocking forever on one channel, improving concurrency by making programs more responsive and less prone to deadlocks.