23.13 Modules and Crates
Modules and Crates
Overview
Modules and crates in Rust help organize code into reusable and maintainable units.
Topics
- Defining Modules
- Using
modanduse - Crates and the Cargo Package Manager
Examples
Modules
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
let result = math::add(2, 3);
println!("Result: {}", result);
Crates
# Add dependencies in Cargo.toml
[dependencies]
rand = "0.8"
# Use the crate in your code
use rand::Rng;
let mut rng = rand::thread_rng();
let n: u32 = rng.gen_range(1..101);
println!("Random number: {}", n);