Named return values in Go - Time & Space Complexity
Let's see how using named return values affects how long a Go function takes to run.
We want to know if naming return values changes the work done as input grows.
Analyze the time complexity of the following code snippet.
func sumAndCount(nums []int) (sum int, count int) {
for _, num := range nums {
sum += num
count++
}
return
}
This function adds all numbers in a list and counts how many numbers there are, using named return values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, the function does more work because it looks at each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions and counts |
| 100 | About 100 additions and counts |
| 1000 | About 1000 additions and counts |
Pattern observation: The work grows directly with the size of the input list.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the list.
[X] Wrong: "Using named return values makes the function slower because it adds extra work."
[OK] Correct: Named return values are just labels for the results and do not add extra loops or calculations, so they don't change how long the function takes.
Understanding how named return values work helps you explain your code clearly and shows you know how Go handles function results efficiently.
"What if we added another loop inside the function that also goes through the list? How would the time complexity change?"
Practice
named return values in Go functions?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 DQuick Check:
Named return values improve readability = D [OK]
- Thinking named returns change return types
- Believing named returns prevent returning values
- Confusing named returns with automatic type conversion
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 CQuick Check:
Named returns syntax = (name type) [OK]
- Placing type before name in return signature
- Omitting parentheses around return values
- Using invalid order like 'int sum'
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)
}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 BQuick Check:
Named returns default zero + error string = A [OK]
- Expecting result to be 10 when dividing by zero
- Assuming runtime error instead of handled error string
- Forgetting named returns default zero values
func multiply(a, b int) (product int) {
product = a * b
return product
}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 AQuick Check:
Named returns allow bare 'return' [OK]
- Returning named variable explicitly instead of bare return
- Thinking named returns require multiple return values
- Believing assignment to named returns is disallowed
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)
}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.Final Answer:
Sum: 12, Count: 3 -> Option AQuick Check:
Sum positive nums = 12, Count positive nums = 3 [OK]
- Including zero or negative numbers in sum and count
- Forgetting to return named values
- Miscounting positive numbers in slice
Ready to prove it?
Pass the test and this pattern moves unknown
