Concept Flow - Why modules are used
Start Program
Define Module
Add Functions/Variables
Use Module in Main
Run Program
Organized Code & Avoid Name Conflicts
Modules group related code together, keep code organized, and prevent name conflicts.
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
fn main() {
let sum = math::add(2, 3);
println!("Sum is {}", sum);
}| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define module 'math' | Module created | math module ready |
| 2 | Define function 'add' inside 'math' | Function available | add(a,b) adds two numbers |
| 3 | Call math::add(2, 3) in main | Function called with a=2, b=3 | Returns 5 |
| 4 | Assign result to 'sum' | sum = 5 | sum holds value 5 |
| 5 | Print 'Sum is 5' | Output to console | Sum is 5 |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| sum | undefined | 5 | 5 | 5 |
Modules group related code. Use 'mod' to define modules. Use 'pub' to make items accessible outside. Access with module_name::item_name. Keeps code organized and avoids name conflicts.