0
0
Rustprogramming~5 mins

Custom error types in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom error types
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

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
10About 10 steps to copy/store the string
100About 100 steps
1000About 1000 steps

Pattern observation: The time grows roughly in direct proportion to the size of the string stored in the error.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how error creation time grows helps you write efficient Rust code and explain your choices clearly in interviews.

Self-Check

What if the custom error stored a fixed-size number instead of a string? How would the time complexity change?