Consider the following Go code. What will it print when run?
package main import "fmt" func foo() int { fmt.Println("foo start") defer fmt.Println("foo defer") fmt.Println("foo end") return 1 } func main() { fmt.Println("main start") result := foo() fmt.Println("result:", result) fmt.Println("main end") }
Remember that deferred functions run after the surrounding function returns but before it fully exits.
The function foo prints "foo start", then "foo end", then returns 1. The deferred print "foo defer" runs after the return statement but before foo fully exits. So the order inside foo is: start, end, defer. The main function prints before and after calling foo.
What will this Go program print?
package main import "fmt" func countdown(n int) { if n == 0 { fmt.Println("Blastoff!") return } fmt.Println(n) countdown(n - 1) } func main() { countdown(3) }
Think about the order of prints and when the function returns.
The function prints the current number, then calls itself with one less. When it reaches zero, it prints "Blastoff!" and returns. So the numbers print in descending order, then "Blastoff!".
Examine the code below. Why does it panic at runtime?
package main import "fmt" func main() { var f func() f() fmt.Println("Done") }
Think about what happens when you call a function variable that has not been assigned.
The variable f is declared as a function type but is not assigned any function. Calling f() tries to call a nil function pointer, which causes a runtime panic.
Which code snippet correctly defines and immediately calls an anonymous function that prints "Hello"?
Anonymous functions need parentheses after their definition to be called immediately.
Option C correctly defines an anonymous function and immediately calls it with (). Option C is missing parentheses after func. Option C defines the function but does not call it. Option C uses invalid syntax.
Given the code below, what is the value of x after modify(&x) is called?
package main import "fmt" func modify(p *int) { *p += 10 defer func() { *p *= 2 }() *p += 5 } func main() { x := 5 modify(&x) fmt.Println(x) }
Remember that deferred functions run after the surrounding function returns.
Inside modify, *p starts at 5. Then *p += 10 makes it 15. Then *p += 5 makes it 20. The deferred function runs after modify returns and doubles *p to 40.