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?"