Using unwrap and expect in Rust - Time & Space Complexity
We want to see how using unwrap and expect affects the speed of Rust code.
Does calling unwrap or expect change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
fn find_first_even(numbers: &[i32]) -> i32 {
numbers.iter()
.find(|&&x| x % 2 == 0)
.expect("No even number found")
}
fn main() {
let nums = vec![1, 3, 5, 6, 7];
let first_even = find_first_even(&nums);
println!("First even number: {}", first_even);
}
This code looks for the first even number in a list and uses expect to get the value or show an error.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over the list to find the first even number.
- How many times: Up to n times, where n is the length of the list, until an even number is found.
As the list gets bigger, the search might take longer if the even number is near the end or missing.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The time grows roughly in a straight line with the input size until the first even number is found.
Time Complexity: O(n)
This means the time to find the first even number grows linearly with the size of the list.
[X] Wrong: "unwrap or expect make the code run faster because they skip error handling."
[OK] Correct: unwrap and expect only affect what happens after the search; the search itself still checks elements one by one, so time depends on input size.
Understanding how unwrap and expect behave helps you explain error handling and performance clearly, a useful skill in many coding discussions.
"What if we replaced expect with unwrap_or to provide a default value? How would the time complexity change?"