Custom error types in Rust - Time & Space Complexity
When we create custom error types in Rust, we want to know how the time to create or handle these errors changes as our program grows.
We ask: How does the cost of working with custom errors grow when the program or input size increases?
Analyze the time complexity of the following Rust code defining and using a custom error type.
#[derive(Debug)]
enum MyError {
NotFound(String),
PermissionDenied,
}
fn check_access(user: &str) -> Result<(), MyError> {
if user == "admin" {
Ok(())
} else {
Err(MyError::NotFound(user.to_string()))
}
}
This code defines a custom error type and a function that returns an error or success based on input.
Look for operations that repeat or grow with input size.
- Primary operation: Creating or returning the custom error value.
- How many times: Once per function call, no loops or recursion here.
The time to create or return the error depends on the size of data inside the error, like the string in NotFound.
| Input Size (length of string) | Approx. Operations |
|---|---|
| 10 | About 10 steps to copy/store the string |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The time grows roughly in direct proportion to the size of the string stored in the error.
Time Complexity: O(n)
This means the time to create or handle the error grows linearly with the size of the data inside the error.
[X] Wrong: "Creating a custom error always takes constant time no matter what."
[OK] Correct: If the error holds data like strings, the time depends on how big that data is, so it can grow with input size.
Understanding how error creation time grows helps you write efficient Rust code and explain your choices clearly in interviews.
What if the custom error stored a fixed-size number instead of a string? How would the time complexity change?