Propagating errors with ? in Rust - Time & Space Complexity
When using the ? operator in Rust, we want to know how it affects the time it takes for a function to run.
Specifically, we ask: does using ? add extra work as the input grows?
Analyze the time complexity of the following code snippet.
fn read_and_parse(input: &str) -> Result {
let num_str = input.trim();
let num = num_str.parse::()?;
Ok(num)
}
This function trims a string, tries to parse it as a number, and uses ? to return errors early.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
parsemethod internally processes the string characters once. - How many times: It runs once per function call, no loops or recursion here.
The time to parse grows roughly with the length of the input string, since each character is checked.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The work grows linearly as the input string gets longer.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input string.
[X] Wrong: "Using ? adds extra loops or slows down the function significantly."
[OK] Correct: The ? operator just returns errors early without extra looping; it does not add repeated work.
Understanding how error handling affects performance shows you can write clean code without guessing about speed.
"What if the function called parse multiple times on different parts of the input? How would the time complexity change?"