Sub topic 2
Splitting Modules Across Files
Assume basic Rust syntax, ownership, borrowing, Result, and familiarity with cargo build and cargo run.
Splitting modules across files
A module declaration without a body tells Rust to load another file. For example, src/lib.rs can contain:
pub mod geometry;Rust then looks for src/geometry.rs or src/geometry/mod.rs. If geometry.rs contains pub mod shapes;, Rust loads src/geometry/shapes.rs.
Items are private by default. Add pub when parent modules or external crates need access.
Re-exports and public APIs
A re-export uses pub use to expose an item through a shorter path:
mod geometry;
pub use geometry::shapes::Square;
pub fn area(s: &Square) -> u32 {
s.0 * s.0
}Callers can use my_crate::Square instead of knowing the internal path. This lets you reorganize implementation files without changing the public API.
| Declaration | Meaning |
|---|---|
| `pub` | Visible to anyone who can access the enclosing module |
| `pub(crate)` | Visible throughout the current crate |
| `pub(super)` | Visible to the parent module |
A package with a library and binary
One Cargo package can build several crates. src/lib.rs defines the library crate, while src/main.rs defines the default binary crate. The binary can call the library through the package name:
use my_crate::area;
fn main() {
println!("{}", area(3, 4));
}Dependencies and features
Normal dependencies go under [dependencies]. Development-only tools belong under [dev-dependencies]. Optional dependencies can be enabled by a feature.
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
pretty_assertions = "1"
[features]
default = []
serde = ["dep:serde"]A feature is a named compile-time choice. Code can use #[cfg(feature = "serde")] to include code only when that feature is enabled.
Workspaces
A workspace groups related packages. They share a lockfile and build directory:
[workspace]
resolver = "2"
members = ["core", "cli"]A member can depend on another with core = { path = "../core" }.
Unit tests next to code
Put unit tests in a #[cfg(test)] module. They can access private implementation details:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn area_is_correct() {
assert_eq!(area(3, 4), 12);
}
}Exercise
Why might a crate re-export geometry::shapes::Square as Square?
Show answer
To provide a stable, shorter public path while hiding the internal module layout.