Generic functions in Rust - Time & Space Complexity
We want to see how the time a generic function takes changes as the input size grows.
How does using a generic type affect the speed when the function runs?
Analyze the time complexity of the following code snippet.
fn print_items(items: &[T]) {
for item in items {
println!("{}", item);
}
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
print_items(&numbers);
}
This function prints each item in a list, using a generic type that can be any printable value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the input slice.
As the list gets bigger, the function prints more items, so it takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The time grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items to print.
[X] Wrong: "Using generics makes the function slower because it has to handle many types."
[OK] Correct: The generic function runs the same loop regardless of type; the time depends on input size, not the type itself.
Understanding how generic functions behave helps you explain code efficiency clearly and confidently in real projects and interviews.
"What if we changed the function to print pairs of items instead of single items? How would the time complexity change?"