As Rust projects grow in complexity, organizing code becomes essential. Today, I dived deep into Rust's powerful module systemβhow packages, crates, and modules help structure code for better readability, maintainability, and reuse.
π¦ Packages & Crates
β Crate:
A crate is the smallest unit of compilation in Rust. It can be:
- A binary crate: builds to an executable (main.rs)
- A library crate: provides reusable logic (lib.rs)
# Create a new binary crate
cargo new my_project
β Package:
A package is a bundle of one or more crates.
- Contains a Cargo.toml file.
- Can have multiple binary crates, one library crate.
π§ Key Point: By convention:
- src/main.rs β binary crate
- src/lib.rs β library crate
Want multiple binaries? Add them in src/bin/.
π Modules and File Structure
Modules help you logically group related code and control visibility.
mod garden; // This tells Rust to look for src/garden.rs or src/garden/mod.rs
In garden.rs, you can further define submodules:
pub mod vegetables;
And in vegetables.rs:
#[derive(Debug)]
pub struct Asparagus {}
π Module Tree Example:
crate
βββ garden
βββ vegetables
βββ Asparagus
π Privacy: Public vs Private
By default, items inside a module are private. Use pub to make them public.
pub mod garden {
pub mod vegetables {
#[derive(Debug)]
pub struct Asparagus {}
}
}
To access:
use crate::garden::vegetables::Asparagus;
fn main() {
let veggie = Asparagus {};
println!("{:?}", veggie);
}
π§ Paths in Modules
Absolute Path:
crate::garden::vegetables::Asparagus
Relative Path:
super::vegetables::Asparagus
Use use to simplify:
use crate::garden::vegetables::Asparagus;
Then:
let veg = Asparagus {};
π§ͺ Module Cheat Sheet
- Start with mod your_module; in the crate root.
- Place module files in:
- src/your_module.rs
- src/your_module/mod.rs
- Declare submodules in sub-files.
- Use pub for visibility.
- Simplify paths with use.
π Real Example File Structure
backyard/
βββ Cargo.toml
βββ src/
βββ main.rs # crate root (binary)
βββ garden.rs # contains `pub mod vegetables`
βββ garden/
βββ vegetables.rs
And your code:
main.rs
use crate::garden::vegetables::Asparagus;
pub mod garden;
fn main() {
let plant = Asparagus {};
println!("I'm growing {:?}", plant);
}
garden.rs
pub mod vegetables;
vegetables.rs
#[derive(Debug)]
pub struct Asparagus;
π§ Summary
Todayβs learning focused on organizing Rust projects for scale and clarity.
- π¦ Packages group crates.
- π§± Crates are the compilation units.
- π§ Modules help logically separate features.
- π Visibility is opt-in (pub).
- π§΅ Paths and use streamline access to items.
Rust enforces structure and clarity by design. Mastering this early on helps you grow clean, robust codebases.
π Tomorrow, Iβll dive deeper into visibility, pub use, and real-world structuring in Rust!
Let me know your thoughts or questions in the comments! π
Top comments (0)