Consider the following Go code that launches two goroutines. What will be printed?
package main import ( "fmt" "time" ) func main() { go fmt.Println("Hello from goroutine 1") go fmt.Println("Hello from goroutine 2") time.Sleep(100 * time.Millisecond) fmt.Println("Main function finished") }
Remember that goroutines run concurrently and time.Sleep allows them time to execute before the main function exits.
The two goroutines print their messages concurrently. The time.Sleep call pauses the main goroutine long enough for both goroutines to run and print their messages before the main function prints its final message.
In Go, what is the behavior when you read from a closed channel?
Think about how channels signal no more values will be sent.
When a channel is closed, reading from it returns the zero value of the channel's type immediately and does not block. This allows goroutines to detect the channel closure.
Examine the following Go code. What causes the deadlock?
package main func main() { ch := make(chan int) ch <- 1 <-ch }
Consider how unbuffered channels block on send and receive.
The channel is unbuffered, so sending blocks until another goroutine receives. Since the send happens in main and no other goroutine receives yet, the program deadlocks.
Which of the following Go code snippets correctly declares and starts a goroutine that prints "Hi"?
Remember the syntax for anonymous functions and starting goroutines.
Option A correctly defines an anonymous function and immediately calls it as a goroutine. Other options have syntax errors or misuse the go keyword.
Given the following Go code, how many values will be received and printed?
package main import "fmt" func main() { ch := make(chan int, 3) ch <- 10 ch <- 20 close(ch) count := 0 for v := range ch { fmt.Println(v) count++ } fmt.Println("Total received:", count) }
Think about how many values were sent before closing the channel.
The channel buffer size is 3, but only 2 values (10 and 20) were sent before closing. The range loop receives these 2 values and then stops.