Consider this Go program that uses a channel to synchronize goroutines. What will it print?
package main import ( "fmt" ) func main() { ch := make(chan string) go func() { ch <- "hello" }() msg := <-ch fmt.Println(msg) }
Think about how the channel is used to pass data between goroutines.
The goroutine sends the string "hello" into the channel. The main goroutine receives it and prints it. So the output is "hello".
What will this Go program print?
package main import ( "fmt" ) func main() { ch := make(chan int) go func() { ch <- 42 close(ch) }() val, ok := <-ch fmt.Println(val, ok) val, ok = <-ch fmt.Println(val, ok) }
Remember what happens when you read from a closed channel in Go.
Reading from a closed channel returns the zero value and false for the second value. The first read gets 42 and true, the second read gets 0 and false.
Examine this Go program. It deadlocks at runtime. Why?
package main func main() { ch := make(chan int) ch <- 1 <-ch }
Think about how unbuffered channels block on send and receive.
The send operation blocks because no goroutine is ready to receive from the unbuffered channel. This causes a deadlock.
Choose the correct Go code to create a buffered channel of integers with capacity 3.
Recall the syntax of make for buffered channels.
make(chan int, 3) creates a buffered channel with capacity 3. The second argument is the buffer size as an integer.
Given this Go code, how many items remain in the channel after execution?
package main import ( "fmt" ) func main() { ch := make(chan int, 5) for i := 0; i < 3; i++ { ch <- i } <-ch ch <- 10 fmt.Println(len(ch)) }
Count how many sends and receives happen on the buffered channel.
Initially 3 items sent, then 1 item received (removes one), then 1 item sent again. So total items in channel: 3 - 1 + 1 = 3. But len(ch) returns 3, so answer is 3.