Defining modules in Rust - Time & Space Complexity
When we define modules in Rust, we organize code into parts. Understanding time complexity here means seeing how the program's work grows when using modules.
We want to know: does adding modules change how long the program takes to run?
Analyze the time complexity of the following code snippet.
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
fn main() {
let result = math::add(5, 3);
println!("{}", result);
}
This code defines a module named math with a function add. The main function calls this add function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single function call to
addinside the module. - How many times: Exactly once in this example.
Since the module just holds a simple function, the work done does not grow with input size here.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 function call |
| 100 | 1 function call |
| 1000 | 1 function call |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is, because the module just groups code without adding loops or repeated work.
[X] Wrong: "Using modules makes the program slower because it adds extra steps."
[OK] Correct: Modules only organize code and do not add repeated work or loops by themselves, so they don't slow down the program.
Knowing that modules organize code without changing how much work the program does helps you explain clean code design and performance clearly in interviews.
"What if the module contained a loop inside the function? How would the time complexity change?"