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?"
Practice
let x = 5; without specifying a type?Solution
Step 1: Understand Rust's default integer type
Rust usesi32as the default integer type when no type is specified.Step 2: Apply type inference to
Since 5 is an integer literal, Rust inferslet x = 5;xto bei32automatically.Final Answer:
Rust guesses the type ofxasi32based on the value 5. -> Option DQuick Check:
Type inference =i32for integer literals [OK]
- Thinking Rust requires explicit types always
- Assuming default type is string
- Believing missing types cause syntax errors
Solution
Step 1: Identify valid floating-point syntax
In Rust, floating-point literals use a dot (.) as decimal separator, so3.14is valid.Step 2: Check type inference usage
Writinglet num = 3.14;lets Rust inferf64type automatically.Final Answer:
let num = 3.14; -> Option CQuick Check:
Floating-point literals inferf64by default [OK]
- Using comma instead of dot for decimals
- Confusing string literals with numbers
- Unnecessarily specifying type when inference works
let x = 10;
let y = 20.5;
let z = x as f64 + y;
println!("{}", z);Solution
Step 1: Understand type casting
Variablexisi32,yisf64. Castingx as f64converts it to floating-point.Step 2: Calculate the sum
After casting,10.0 + 20.5 = 30.5. Theprintln!prints this value.Final Answer:
30.5 -> Option AQuick Check:
Cast int to float, then add = 30.5 [OK]
- Expecting integer addition without cast
- Assuming implicit cast without
as - Confusing output format with concatenation
let a = 5; let b = 2.0; let c = a + b;
Solution
Step 1: Check variable types
aisi32(integer),bisf64(floating-point).Step 2: Understand addition rules in Rust
Rust does not allow adding different numeric types directly; explicit casting is needed.Final Answer:
Cannot add integer and floating-point without casting. -> Option AQuick Check:
Mixed-type addition requires cast [OK]
- Ignoring type mismatch errors
- Assuming implicit conversion between int and float
- Overlooking Rust's strict type rules
result? let values = vec![1, 2, 3]; let result: Vec<f64> = values.iter().map(|&x| x as f64 * 1.5).collect();
Solution
Step 1: Analyze the iterator and map closure
values.iter()produces references&i32. The closure|&x| x as f64 * 1.5dereferences and castsxtof64, then multiplies.Step 2: Collect into specified type
Thecollect()call collects results intoVec<f64>as explicitly annotated.Final Answer:
Vec<f64> -> Option BQuick Check:
Mapping with cast and collecting matches annotated type [OK]
- Confusing iterator item types with collected vector type
- Missing dereference in closure causing type errors
- Assuming collect infers wrong type without annotation
Ready to prove it?
Pass the test and this pattern moves unknown
