Consider the following Go program that uses channels. What will it print?
package main import ( "fmt" ) func main() { ch := make(chan int, 2) ch <- 1 ch <- 2 close(ch) for v := range ch { fmt.Print(v) } }
Remember that closing a channel allows range to receive remaining buffered values.
The channel is buffered with capacity 2. It receives 1 and 2, then closes. The range loop reads all values until the channel is empty, printing "12".
In Go, what is the recommended way to handle errors returned by functions?
Think about Go's philosophy of explicit error handling.
Go encourages returning error values and checking them explicitly to handle errors gracefully and clearly.
Analyze the following Go code snippet. What error will it cause when compiled?
package main func main() { var x int if x := 5; x > 3 { println(x) } println(x) }
Consider variable shadowing and scopes in Go.
The 'x' inside the if statement shadows the outer 'x'. Inside the if block, x is 5 and prints 5. Outside, the original x is 0 and prints 0.
Which of the following Go code snippets will cause a runtime panic when executed?
package main func main() { var x int if x := 5; x > 3 { println(x) } println(x) }
Remember that maps must be initialized with make() or a map literal before you can assign to them.
Option D declares a nil map (var m map[string]int) and tries to assign m["a"] = 1, which causes a runtime panic: 'assignment to entry in nil map'. Options B, C, and D all properly initialize the map before assignment.
Consider this Go program. How many goroutines are alive after the main function finishes?
package main import ( "fmt" "time" ) func worker(done chan bool) { time.Sleep(100 * time.Millisecond) done <- true } func main() { done := make(chan bool) for i := 0; i < 3; i++ { go worker(done) } for i := 0; i < 3; i++ { <-done } fmt.Println("All workers done") }
Think about when goroutines finish and the main function exits.
The main function waits for all 3 worker goroutines to send done signals before printing. After that, all worker goroutines have finished, so no goroutines remain alive.