0
0
Goprogramming~20 mins

Named return values in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Named Return Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
A0 0
B7 12
C7 0
DCompilation error
Attempts:
2 left
💡 Hint
Named return values can be set inside the function and returned with a naked return.
Predict Output
intermediate
2: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)
}
A7 10
B0 0
C5 10
DCompilation error
Attempts:
2 left
💡 Hint
Named return values can be changed before the naked return statement.
🔧 Debug
advanced
2: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
}
AIt returns zero because named return values are ignored when explicit return values are given.
BIt returns zero because the function has no return statement.
CIt returns zero because the function does not assign values to sum and diff.
DIt returns zero because the return statement is missing parentheses.
Attempts:
2 left
💡 Hint
Check how named return values interact with explicit return values.
📝 Syntax
advanced
2: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
}
Afunc example() (a int, b int) { a := 1; b := 2; return }
Bfunc example() (a int, b int) { a = 1; b = 2; return }
Cfunc example() (a int, b int) { a, b = 1, 2; return }
Dfunc example() (a int, b int) { a = 1; b = 2; return a, b }
Attempts:
2 left
💡 Hint
Check variable declaration and assignment rules with named return values.
🚀 Application
expert
2: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
}
ACompilation error
B0
C1
D3
Attempts:
2 left
💡 Hint
The loop adds keys 'a', 'b', 'c' with values 0,1,2 to the map.