Challenge - 5 Problems
Named Return Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of function with named return values and naked return
What is the output of this Go program?
Go
package main import "fmt" func calculate() (sum int, product int) { sum = 3 + 4 product = 3 * 4 return } func main() { s, p := calculate() fmt.Println(s, p) }
Attempts:
2 left
💡 Hint
Named return values can be set inside the function and returned with a naked return.
✗ Incorrect
The function calculate() uses named return values sum and product. They are assigned values inside the function. The naked return returns these values. So the output is '7 12'.
❓ Predict Output
intermediate2:00remaining
Effect of modifying named return values before return
What will this Go program print?
Go
package main import "fmt" func getValues() (x int, y int) { x = 5 y = 10 x += 2 return } func main() { a, b := getValues() fmt.Println(a, b) }
Attempts:
2 left
💡 Hint
Named return values can be changed before the naked return statement.
✗ Incorrect
The function sets x=5 and y=10, then increments x by 2 making x=7. The naked return returns x=7 and y=10.
🔧 Debug
advanced2:00remaining
Why does this function return zero values?
This Go function is intended to return the sum and difference of two integers using named return values. Why does it always return zero for both values?
func compute(a, b int) (sum int, diff int) {
return sum, diff
}
Go
func compute(a, b int) (sum int, diff int) { return sum, diff }
Attempts:
2 left
💡 Hint
Check how named return values interact with explicit return values.
✗ Incorrect
Named return values `sum` and `diff` are zero-initialized. The function does not assign values to them before explicitly returning `sum, diff`, so zero values are returned.
📝 Syntax
advanced2:00remaining
Identify the syntax error with named return values
Which option contains a syntax error in this Go function with named return values?
Go
func example() (a int, b int) { a = 1 b = 2 return }
Attempts:
2 left
💡 Hint
Check variable declaration and assignment rules with named return values.
✗ Incorrect
Option A uses ':=' to declare a and b inside the function, but a and b are already declared as named return values. Using ':=' redeclares them locally, which is not allowed here and causes a syntax error.
🚀 Application
expert2:00remaining
How many items are in the returned map from this function?
Consider this Go function that returns a map using named return values. How many key-value pairs does the returned map contain?
Go
func createMap() (result map[string]int) { result = make(map[string]int) for i := 0; i < 3; i++ { result[string('a'+i)] = i } return }
Attempts:
2 left
💡 Hint
The loop adds keys 'a', 'b', 'c' with values 0,1,2 to the map.
✗ Incorrect
The function initializes an empty map and adds three entries with keys 'a', 'b', 'c' and values 0,1,2. So the map contains 3 key-value pairs.