Modules and Visibility
Module Path
Calling a Public Function
A module groups related items. pub makes a function callable from outside the module, and module::item names the path.
Program
Play the program to choose a multiplication factor and call a public function through its module path.
module_path.rs
Replay: real traced execution (multi-file project)
mod math {
pub fn scale(value: i32, factor: i32) -> i32 {
value * factor
}
}
fn main() {
let factor = 3;
let result = math::scale(5, factor);
println!("{result}");
}
mod math {
pub fn scale(value: i32, factor: i32) -> i32 {
value * factor
}
}
fn main() {
let factor = 2;
let result = math::scale(5, factor);
println!("{result}");
}
mod math {
pub fn scale(value: i32, factor: i32) -> i32 {
value * factor
}
}
fn main() {
let factor = 4;
let result = math::scale(5, factor);
println!("{result}");
}
factor ← 3
7fn main() {8 let facto→ 3r = 3; //@factor=3, 2, 49 let result = math::scale(5, facto3r);10 println!("{result}");fn scale(value: i32, factor: i32) -> i32
1mod math {2 pub fn scale(value: i32, factor: i32) -> i32 {3 valu5e * facto3r4 }5}result ← 15
8 let factor = 3; //@factor=3, 2, 49 let resul→ 15t = math::scale(5, facto3r);10 println!("{result}");11}output15
factor ← 2
7fn main() {8 let facto→ 2r = 2;9 let result = math::scale(5, facto2r);10 println!("{result}");fn scale(value: i32, factor: i32) -> i32
1mod math {2 pub fn scale(value: i32, factor: i32) -> i32 {3 valu5e * facto2r4 }5}result ← 10
8 let factor = 2;9 let resul→ 10t = math::scale(5, facto2r);10 println!("{result}");11}output10
factor ← 4
7fn main() {8 let facto→ 4r = 4;9 let result = math::scale(5, facto4r);10 println!("{result}");fn scale(value: i32, factor: i32) -> i32
1mod math {2 pub fn scale(value: i32, factor: i32) -> i32 {3 valu5e * facto4r4 }5}result ← 20
8 let factor = 4;9 let resul→ 20t = math::scale(5, facto4r);10 println!("{result}");11}output20
mod
`mod math` defines a nested module.
pub fn
`pub fn scale` can be called from outside `math`.
path
`math::scale` names the function through the module path.