Modules, Crates and Cargo
Crates and modules, visibility, `use` paths, Cargo dependencies, features and workspaces, editions, clippy and rustfmt.
13 questions
JuniorTheoryCommonWhich versions does the line serde = "1.0" in Cargo.toml allow?
Which versions does the line serde = "1.0" in Cargo.toml allow?
Any 1.x release from 1.0.0 up, but never 2.0
Common mistakes
- ✗Expecting exactly 1.0.0, as if the line pinned it: a bare version is a caret requirement, so Cargo may choose any compatible 1.x release, such as 1.0.200 or 1.4.0.
- ✗Expecting 2.0 to count as a newer allowed version: a new major version may break the API, so
"1.0"stops before 2.0.0.
Follow-up questions
- →Which version does Cargo pick for
"1.0"on the first build, and which file records it? - →Which range does
"0.3"allow, and why does a 0.x version behave differently?
JuniorTheoryCommonHow do mod, use, paths and pub work in Rust's module system?
How do mod, use, paths and pub work in Rust's module system?
mod net; declares a module whose body lives in net.rs or net/mod.rs. Items are private to their module unless marked pub or pub(crate); paths start at crate::, super:: or self::, and use brings a path into scope.
Common mistakes
- ✗Expecting every file in
src/to become a module without amoddeclaration - ✗Assuming items are public by default, as in Python
- ✗Treating
uselike#include, though it only shortens a path to an already declared item
Follow-up questions
- →When would you choose
pub(crate)overpubfor a helper function? - →Why can a child module call its parent's private function, but not the other way round?
JuniorTheoryCommonPackage, crate, module: how do they differ, and which is compiled as a unit?
Package, crate, module: how do they differ, and which is compiled as a unit?
A crate is the unit of compilation: rustc builds one tree of modules from a root file into a library or a binary. A package is a Cargo.toml with one or more crates — at most one library, any number of binaries. Modules organise code inside a crate.
Common mistakes
- ✗Thinking each file is compiled on its own, as in C or C++
- ✗Believing one package cannot hold a library and a binary at the same time
- ✗Using crate to mean only a library downloaded from crates.io
Follow-up questions
- →How does Cargo find a package's binary crates without listing them in
Cargo.toml? - →Why do projects often keep
main.rsthin and move the logic intolib.rs?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
start waterbecausegardensits in the same file asmain: an item withoutpubis private to its module, somainmay not callgarden::water(E0603). - ✗Expecting
startto print before the error: rustc checks the whole program while building, before anything runs, so a private call stops the build and nothing runs.
Follow-up questions
- →Which single word would you add so that the program prints
startandwater? - →Could another function inside
gardencallwaterwithout that change?
MiddleTheoryCommonWhat does Cargo.lock record that Cargo.toml does not, and why commit it?
What does Cargo.lock record that Cargo.toml does not, and why commit it?
Cargo.toml states version ranges; Cargo.lock records the exact version Cargo resolved for every crate in the graph. Committed, it gives everyone the same build, and --locked fails CI if it is stale. Dependents ignore a library's lock file.
Common mistakes
- ✗Believing a library's
Cargo.lockdecides what its dependents build with - ✗Thinking
cargo buildrefreshesCargo.lockto the newest versions, when onlycargo updateor a changed manifest does - ✗Expecting the lock file to pin only direct dependencies, though it records the whole graph
Follow-up questions
- →How would you check in CI that your library still builds with the newest allowed dependency versions?
- →Why does
cargo installpick the newest dependencies unless you pass--locked?
MiddlePerformanceOccasionalWhy do Rust builds take long, and what actually makes them faster?
Why do Rust builds take long, and what actually makes them faster?
Each crate is one compilation unit, and monomorphized generics plus LLVM take most of the time. Profile with cargo build --timings, split big crates to compile in parallel, use cargo check while editing and keep incremental debug builds.
Common mistakes
- ✗Blaming the borrow checker, when code generation for monomorphized generics and LLVM usually dominates
- ✗Merging crates to cut their number, which removes parallelism and makes every edit rebuild more code
- ✗Guessing at the slow part instead of reading the
cargo build --timingsreport
Follow-up questions
- →How does a thin generic wrapper around a non-generic inner function cut compile time?
- →What does the
cargo build --timingsreport show that helps you decide where to split a crate?
MiddleTheoryOccasionalHow do Cargo features work, and why must every feature be additive?
How do Cargo features work, and why must every feature be additive?
A feature is a flag in [features] that enables #[cfg(feature = "x")] code or an optional dependency via dep:; default stays on unless default-features = false. Cargo unions features across the graph, so enabling one must never remove code.
Common mistakes
- ✗Adding a feature that disables something, such as
no-alloc, which breaks crates that need it once features are unioned - ✗Expecting each dependent to get the crate built with only its own features
- ✗Forgetting that
defaultfeatures stay on until a dependent setsdefault-features = false
Follow-up questions
- →Why does the
dep:prefix stop an optional dependency from becoming a feature of its own? - →How would you check that every combination of your crate's features still compiles?
MiddleTheoryOccasionalWhat is a Cargo workspace, and why use one for a multi-crate project?
What is a Cargo workspace, and why use one for a multi-crate project?
A workspace is a root Cargo.toml with a [workspace] table listing member packages. They share one Cargo.lock and one target/, so every crate uses the same dependency versions and each is built once; members depend on each other by path.
Common mistakes
- ✗Expecting each member to keep its own
Cargo.lockandtarget/ - ✗Thinking members can use each other's items without a
pathdependency - ✗Believing a workspace merges its members into one crate
Follow-up questions
- →How does
[workspace.dependencies]keep one version of a crate across all members? - →Why can building one member alone enable different features than building the whole workspace?
MiddleTheoryOccasionalHow do #[cfg] and cfg! differ, and what is a build.rs script for?
How do #[cfg] and cfg! differ, and what is a build.rs script for?
#[cfg(...)] drops the marked item when the condition is false, so that code is never compiled; cfg!(...) is just a bool, and both branches must compile. build.rs runs before the crate compiles to generate code, link C libraries or set cfgs.
Common mistakes
- ✗Wrapping a call to a
#[cfg(windows)]function inif cfg!(windows), which still fails to compile on Linux because that branch is type-checked - ✗Thinking
#[cfg]is evaluated at run time - ✗Emitting a custom cfg from
build.rswithoutcargo::rustc-check-cfg, which triggers theunexpected_cfgswarning
Follow-up questions
- →How does
build.rspass a custom cfg such asfast_pathon to the crate? - →Why does a
build.rsusually print acargo::rerun-if-changedline?
MiddleTheoryOccasionalHow do you cross-compile a Rust binary for another platform with Cargo?
How do you cross-compile a Rust binary for another platform with Cargo?
Install the target's std with rustup target add <triple>, then cargo build --target <triple>. The target's linker goes in .cargo/config.toml, platform-only crates in [target.'cfg(...)'.dependencies]; cross does it in a container.
Common mistakes
- ✗Running
cargo build --targetbeforerustup target add, which fails with E0463 because that target'sstdis missing - ✗Forgetting that the target still needs its own linker, especially once a crate links C code
- ✗Gating platform-only crates behind features instead of
[target.'cfg(...)'.dependencies]
Follow-up questions
- →Why does a crate that links a C library make cross-compiling harder?
- →How does the container-based build tool
crossdiffer from a plaincargo build --target?
MiddleTheoryOccasionalWhat does #![no_std] take away from a crate, and when do you need it?
What does #![no_std] take away from a crate, and when do you need it?
#![no_std] links the crate to core instead of std, so files, threads and OS services are gone. core keeps Option, Result, iterators and slices; alloc restores Vec, String and Box with an allocator. It serves firmware and kernels.
Common mistakes
- ✗Thinking
no_stdrules out the heap, thoughallocwith a global allocator restoresVec,StringandBox - ✗Expecting to lose
Option,Resultand iterators, which all live incore - ✗Treating
no_stdas a speed-up for ordinary programs rather than a need of targets without an OS
Follow-up questions
- →Why does a
no_stdbinary have to define its own#[panic_handler]? - →How can a library stay
no_stdby default yet offer an optionalstdfeature?
SeniorTheoryOccasionalWhy can a Cargo feature turn on by itself, and how do you find what enabled it?
Why can a Cargo feature turn on by itself, and how do you find what enabled it?
Cargo builds each crate once per build with the union of features all its dependents request, so another crate in the graph or workspace can turn one on. cargo tree -e features -i <crate> shows who; resolver 2 keeps dev and build deps out of it.
Common mistakes
- ✗Expecting
default-features = falseto win while another dependent in the same build still asks for the defaults - ✗Thinking resolver 2 isolates workspace members from each other's features
- ✗Searching
Cargo.lockfor enabled features, though it records versions and sources only
Follow-up questions
- →Why can
cargo build -p cliandcargo build --workspaceproduce differentclibinaries? - →How does resolver 2 treat a feature that only a dev-dependency enables?
SeniorDesignOccasionalYou maintain geo-core 1.4, a library many crates depend on. A release PR bundles four changes: (1) a method fn area(&self) -> f64 with no default body is added to the public trait Shape; (2) a public field srid: u32 is added to pub struct Point { pub x: f64, pub y: f64 }; (3) the bound of pub fn sort_by_key<T: PartialOrd> is tightened to T: Ord; (4) rust-version is raised from 1.70 to 1.85. Constraints: the team wants to ship it as 1.5.0; dependents use geo-core = "1.4", so their next cargo update picks up 1.5.0; you may restructure the API but must not drop any capability. Decide which changes break SemVer and so need 2.0.0, and how you would reshape the API with the attribute #[non_exhaustive] and the API-design pattern sealed trait so that similar additions can ship as minor releases later.
You maintain geo-core 1.4, a library many crates depend on. A release PR bundles four changes: (1) a method fn area(&self) -> f64 with no default body is added to the public trait Shape; (2) a public field srid: u32 is added to pub struct Point { pub x: f64, pub y: f64 }; (3) the bound of pub fn sort_by_key<T: PartialOrd> is tightened to T: Ord; (4) rust-version is raised from 1.70 to 1.85. Constraints: the team wants to ship it as 1.5.0; dependents use geo-core = "1.4", so their next cargo update picks up 1.5.0; you may restructure the API but must not drop any capability. Decide which changes break SemVer and so need 2.0.0, and how you would reshape the API with the attribute #[non_exhaustive] and the API-design pattern sealed trait so that similar additions can ship as minor releases later.
Changes 1–3 are major: implementors lack area, Point { x, y } literals lack srid, f64 callers fail Ord. A rust-version bump usually ships as minor. Mark structs #[non_exhaustive] and seal traits so new fields and methods stay minor.
Common mistakes
- ✗Assuming any addition is a minor change, though a new required trait method breaks every outside implementor
- ✗Counting a new public field as safe, though it breaks every struct literal and exhaustive pattern outside the crate
- ✗Treating an MSRV bump as automatically major instead of a documented policy usually shipped as minor
Follow-up questions
- →Why is adding
#[non_exhaustive]to the existingPointitself a breaking change? - →How would you catch such breaking changes automatically in CI before publishing a release?