Sub topic 1
Packages, Crates, and What Cargo Builds
Prerequisites
You should know basic Rust syntax, ownership and borrowing, Result, and how to run cargo build and cargo run.
Packages and crates
A package is a project described by Cargo.toml. It can contain one library crate and one or more binary crates. A crate is a compilation unit. The files src/lib.rs and src/main.rs are common crate roots.
Cargo builds each crate separately, resolves its dependencies, and stores build output in target. A binary crate produces an executable. A library crate produces code that other crates can use.
| Item | Meaning |
|---|---|
| Package | Project and its `Cargo.toml` |
| Crate | Unit Cargo compiles |
| Module | Namespace used to organize a crate |
Modules and the module tree
A module creates a namespace. The crate root is the tree's root, and nested modules form branches.
mod shapes {
pub struct Rect {
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn area(&self) -> u32 {
self.width * self.height
}
}
}
fn main() {
let rectangle = shapes::Rect {
width: 3,
height: 4,
};
println!("{}", rectangle.area());
}The path shapes::Rect means “find Rect inside shapes.” A module declaration can also load code from another file, so the module tree can match the directory structure.
Paths and use declarations
A path can be absolute, beginning at the crate root with crate::, or relative to the current module. super:: refers to the parent module.
A use declaration creates a shorter local path:
mod geometry {
pub struct Rect;
}
use geometry::Rect;
fn make_rect() -> Rect {
Rect
}A use declaration changes how you write a path. It does not change ownership or visibility.
Controlling visibility with `pub`
Rust items are private by default. pub makes an item visible through its module's public path. pub(crate) exposes it anywhere in the current crate. pub(super) exposes it to the parent module.
Keep implementation details private and expose only the API callers need. This reduces accidental dependencies between modules.
Exercise
What visibility should you use for a helper needed by several modules in the same crate but not by external users?
Show answer
Use pub(crate).