📖 Scenario: Imagine you are writing a small program to calculate the area and perimeter of a rectangle. You want to create a function that returns both values clearly and simply.
🎯 Goal: Build a Go function that uses named return values to return the area and perimeter of a rectangle given its width and height.
📋 What You'll Learn
Create a function called rectangleMetrics that takes two float64 parameters: width and height.
Use named return values area and perimeter of type float64 in the function signature.
Calculate the area as width * height and perimeter as 2 * (width + height) inside the function.
Return the named values without explicitly listing them in the return statement.
Print the returned area and perimeter values in the main function.
💡 Why This Matters
🌍 Real World
Named return values are useful in real-world Go programs where functions return multiple results, like calculations or data processing.
💼 Career
Understanding named return values helps you write clean, readable Go code, a valuable skill for backend development and system programming jobs.
Progress0 / 4 steps
1
Create the main function and call rectangleMetrics
Write a main function that calls a function named rectangleMetrics with width 5.0 and height 3.0, and stores the results in variables area and perimeter.
Go
Hint
Use area, perimeter := rectangleMetrics(5.0, 3.0) inside main.
2
Define rectangleMetrics with named return values
Define a function called rectangleMetrics that takes two float64 parameters named width and height. Use named return values area and perimeter of type float64 in the function signature.
Go
Hint
Write func rectangleMetrics(width, height float64) (area float64, perimeter float64) to declare named return values.
3
Calculate area and perimeter inside rectangleMetrics
Inside the rectangleMetrics function, calculate area as width * height and perimeter as 2 * (width + height). Assign these values to the named return variables.
Go
Hint
Assign area = width * height and perimeter = 2 * (width + height) before return.
4
Print the area and perimeter in main
In the main function, add import "fmt" at the top and print the area and perimeter values using fmt.Println with the exact text: "Area:", area and "Perimeter:", perimeter.
Go
Hint
Use fmt.Println("Area:", area) and fmt.Println("Perimeter:", perimeter) to print the results.
Practice
(1/5)
1. What is the main benefit of using named return values in Go functions?
easy
A. They prevent the function from returning any value.
B. They allow returning multiple values without specifying types.
C. They automatically convert return types to strings.
D. They make the function's return values easier to understand and use.
Solution
Step 1: Understand named return values
Named return values give explicit names to the outputs of a function, making it clear what each returned value represents.
Step 2: Identify the benefit
Because the return values are named, the code becomes easier to read and understand, especially when returning multiple values.
Final Answer:
They make the function's return values easier to understand and use. -> Option D
Quick Check:
Named return values improve readability = D [OK]
Hint: Named returns clarify output meaning quickly [OK]
Common Mistakes:
Thinking named returns change return types
Believing named returns prevent returning values
Confusing named returns with automatic type conversion
2. Which of the following Go function signatures correctly uses named return values?
easy
A. func add(a, b int) (int sum) { return a + b }
B. func add(a, b int) int sum { return a + b }
C. func add(a, b int) (sum int) { return a + b }
D. func add(a, b int) sum int { return a + b }
Solution
Step 1: Check syntax for named return values
Named return values are declared inside parentheses with the type after the name, like (sum int).
Step 2: Identify correct syntax
func add(a, b int) (sum int) { return a + b } uses (sum int) correctly. Options B, C, and D have incorrect syntax for named returns.
Final Answer:
func add(a, b int) (sum int) { return a + b } -> Option C
Quick Check:
Named returns syntax = (name type) [OK]
Hint: Named returns use (name type) inside parentheses [OK]
Common Mistakes:
Placing type before name in return signature
Omitting parentheses around return values
Using invalid order like 'int sum'
3. What will be the output of this Go program?
package main
import "fmt"
func divide(a, b int) (result int, err string) {
if b == 0 {
err = "division by zero"
return
}
result = a / b
return
}
func main() {
r, e := divide(10, 0)
fmt.Println(r, e)
}
medium
A. 10 division by zero
B. 0 division by zero
C. 0
D. Runtime error
Solution
Step 1: Analyze divide function behavior
If b is zero, err is set to "division by zero" and function returns immediately. result is not set, so defaults to zero.
Step 2: Check main function output
Calling divide(10, 0) returns result=0 and err="division by zero". fmt.Println prints both separated by space.
Final Answer:
0 division by zero -> Option B
Quick Check:
Named returns default zero + error string = A [OK]
Hint: Named returns default zero values if not set [OK]
Common Mistakes:
Expecting result to be 10 when dividing by zero
Assuming runtime error instead of handled error string
Forgetting named returns default zero values
4. Which of the following best improves this Go function using named return values:
func multiply(a, b int) (product int) {
product = a * b
return product
}
medium
A. The return statement should be just 'return' without specifying 'product'.
B. The function must return two values, not one.
C. Named return values cannot be assigned inside the function.
D. The function should not have a return statement.
Solution
Step 1: Understand named return values usage
When using named return values, you can simply use 'return' without arguments to return the named variables.
Step 2: Identify the improvement in return statement
Here, 'return product' is allowed but redundant. The idiomatic way is just 'return' to return named values.
Final Answer:
The return statement should be just 'return' without specifying 'product'. -> Option A
Quick Check:
Named returns allow bare 'return' [OK]
Hint: Use bare 'return' with named return values [OK]
Common Mistakes:
Returning named variable explicitly instead of bare return
Thinking named returns require multiple return values
Believing assignment to named returns is disallowed
5. Given this Go function with named return values, what will be the output?
package main
import "fmt"
func stats(nums []int) (sum, count int) {
for _, n := range nums {
if n > 0 {
sum += n
count++
}
}
return
}
func main() {
s, c := stats([]int{3, -1, 0, 4, 5})
fmt.Printf("Sum: %d, Count: %d\n", s, c)
}
hard
A. Sum: 12, Count: 3
B. Sum: 12, Count: 5
C. Sum: 0, Count: 0
D. Sum: 3, Count: 1
Solution
Step 1: Analyze the loop filtering positive numbers
The function loops over nums and adds only positive numbers to sum and increments count.
Step 2: Calculate sum and count for given slice
Positive numbers are 3, 4, 5. Sum = 3+4+5=12, Count = 3.