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.
math in Rust?mod to declare a module.mod to declare modules = A [OK]mod greetings {
pub fn hello() {
println!("Hello from module!");
}
}
fn main() {
greetings::hello();
}hello is marked pub, so it is accessible outside the module.greetings::hello(), which prints the message.mod tools {
fn hammer() {
println!("Hammering");
}
}
fn main() {
tools::hammer();
}hammer is not marked pub, so it is private to the module.tools::hammer() from main causes an error because the function is private.math and utils. The math module has a public function add that you want to use in utils. How should you structure the code to allow utils to call math::add?add function must be marked pub to be accessible outside math.utils, use use crate::math::add; to bring add into scope for calling.add as pub, and use use crate::math::add; inside utils -> Option DPass the test and this pattern moves unknown