Type inference in Rust - Time & Space Complexity
When Rust figures out the type of a variable automatically, it does some work behind the scenes.
We want to see how the time it takes to guess types grows as the code gets bigger.
Analyze the time complexity of the following code snippet.
fn sum_numbers(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers {
total += num;
}
total
}
let values = vec![1, 2, 3, 4, 5];
let result = sum_numbers(&values);
This code sums a list of numbers. Rust infers the types of variables and function return automatically.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list to add it.
- How many times: Once for each number in the input list.
As the list gets longer, Rust checks each number's type once, then sums them all.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to infer types and sum grows in a straight line with the input size.
[X] Wrong: "Type inference happens instantly no matter how big the input is."
[OK] Correct: Rust must check each element's type in the list, so more items mean more work.
Understanding how type inference scales helps you explain how Rust manages code efficiently behind the scenes.
"What if the function used nested loops over two lists? How would the time complexity change?"