Packages, Crates & Targets
Three words get mixed up constantly in Rust: package, crate and target. Cargo's behaviour only makes sense once they are separate in your head.
| Term | What it is | Example |
|---|---|---|
| Crate | one compilation unit: what one rustc invocation turns into a library or a binary |
the serde library; your main.rs program |
| Package | a folder with a Cargo.toml: a name, a version and one or more targets |
hello with Cargo.toml + src/ |
| Target | one crate a package builds: at most one library, any number of binaries, examples, tests and benches | src/lib.rs, src/main.rs, src/bin/admin.rs |
On crates.io people say "crate" for the whole package; Cargo's own messages say package. Both are fine as long as you know which one you mean.
A library and a binary in one package
cargo new --lib creates a library; cargo new (or --bin) creates a binary. A package can have both: put the shared logic in src/lib.rs and keep src/main.rs thin. The binary uses the library through the package name like any external crate:
cargo new temp --vcs none -q
cd temp
cat > src/lib.rs <<'RS'
/// Converts Celsius to Fahrenheit.
pub fn to_fahrenheit(c: f64) -> f64 {
c * 9.0 / 5.0 + 32.0
}
RS
cat > src/main.rs <<'RS'
fn main() {
for c in [-40.0, 0.0, 37.0] {
println!("{c} C = {} F", temp::to_fahrenheit(c));
}
}
RS
cargo run Compiling temp v0.1.0 (/home/learner/temp)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
Running `target/debug/temp`
-40 C = -40 F
0 C = 32 F
37 C = 98.6 F
Only one Compiling line, but Cargo built two crates: the library temp and the binary temp, which links to it. That split is what lets integration tests, examples and other packages reuse your code: they can all link to a library, but never to a binary.
Several binaries: src/bin/
Every .rs file in src/bin/ (or folder with a main.rs in it) is another binary target, discovered automatically. With more than one binary, cargo run needs to know which one:
cargo new tools --vcs none -q
cd tools
mkdir -p src/bin/report
echo 'fn main() { println!("main tool"); }' > src/main.rs
echo 'fn main() { println!("admin tool"); }' > src/bin/admin.rs
echo 'fn main() { println!("report tool"); }' > src/bin/report/main.rs
cargo run -q 2>&1
cargo run -q --bin admin
cargo run -q --bin report
cargo build -q
ls target/debug | grep -v '\.d