Introduction
Modules help organize code into smaller parts. They make code easier to read and reuse.
Modules help organize code into smaller parts. They make code easier to read and reuse.
mod module_name {
// code here
}
// To use items from the module:
use crate::module_name::item_name;Modules are declared with the mod keyword.
You can access module items using use or by full path.
main.mod greetings {
pub fn hello() {
println!("Hello from module!");
}
}
fn main() {
greetings::hello();
}main.mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
fn main() {
let sum = math::add(5, 3);
println!("Sum is {}", sum);
}This program defines a module tools with a greeting function. The function is called from main.
mod tools {
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
}
fn main() {
tools::greet("Alice");
}Use pub to make functions or variables accessible outside the module.
Modules help avoid cluttering the main program with too much code.
Modules organize code into smaller, manageable parts.
They help reuse code and avoid name conflicts.
Use mod to create modules and pub to share items.
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