Challenge - 5 Problems
Go Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a function returning multiple values
What is the output of this Go program?
Go
package main import "fmt" func divideAndRemainder(a, b int) (int, int) { return a / b, a % b } func main() { q, r := divideAndRemainder(17, 5) fmt.Println(q, r) }
Attempts:
2 left
💡 Hint
Remember that 17 divided by 5 is 3 with remainder 2.
✗ Incorrect
The function divides 17 by 5 returning quotient 3 and remainder 2. The main function prints these values.
❓ Predict Output
intermediate2:00remaining
Output of a function with named return values
What does this Go program print?
Go
package main import "fmt" func swap(x, y string) (a, b string) { a = y b = x return } func main() { a, b := swap("hello", "world") fmt.Println(a, b) }
Attempts:
2 left
💡 Hint
Named return values are assigned inside the function before return.
✗ Incorrect
The function swaps the two strings by assigning named return variables and returns them. So output is 'world hello'.
❓ Predict Output
advanced2:00remaining
Output of recursive function calculating factorial
What is the output of this Go program?
Go
package main import "fmt" func factorial(n int) int { if n <= 1 { return 1 } return n * factorial(n-1) } func main() { fmt.Println(factorial(5)) }
Attempts:
2 left
💡 Hint
Factorial of 5 is 5*4*3*2*1.
✗ Incorrect
The recursive function correctly calculates factorial by multiplying n by factorial of n-1 until base case 1.
❓ Predict Output
advanced2:00remaining
Output of function with variadic parameters
What does this Go program print?
Go
package main import "fmt" func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } func main() { fmt.Println(sum(1, 2, 3, 4)) }
Attempts:
2 left
💡 Hint
Sum all numbers passed as arguments.
✗ Incorrect
The variadic function sums all integers passed and returns the total 10.
❓ Predict Output
expert2:00remaining
Output of function returning a closure capturing variable
What is the output of this Go program?
Go
package main import "fmt" func makeCounter() func() int { count := 0 return func() int { count++ return count } } func main() { counter := makeCounter() fmt.Println(counter()) fmt.Println(counter()) fmt.Println(counter()) }
Attempts:
2 left
💡 Hint
Closures remember the variable state between calls.
✗ Incorrect
The returned function increments and returns count each time, producing 1, 2, 3.