Targets: bins, examples, tests & benches
A package builds a set of targets, each one a separate crate: at most one library, plus binaries, examples, integration tests and benchmarks. Packages, Crates & Targets introduced libraries and binaries; this lesson covers all five kinds, how Cargo finds them, and how to configure them.
The five kinds and where they live
| Kind | Auto-discovered from | Built by | Can use |
|---|---|---|---|
| library | src/lib.rs |
every command | [dependencies] |
| binary | src/main.rs, src/bin/*.rs, src/bin/*/main.rs |
build, run, install |
the library, [dependencies] |
| example | examples/*.rs, examples/*/main.rs |
cargo run --example, cargo test (built, not run) |
library + [dev-dependencies] |
| integration test | tests/*.rs, tests/*/main.rs |
cargo test |
library + [dev-dependencies] |
| benchmark | benches/*.rs |
cargo bench |
library + [dev-dependencies] |
Examples, tests and benches only see the library's public API, exactly like a user of your crate. That's their value: they test what users get.
A package with every kind
bash · try it yourself
cargo new --lib stats --vcs none -q
cd stats
mkdir -p examples tests benches src/bin
cat > src/lib.rs <<'RS'
/// Arithmetic mean, or `None` for an empty slice.
pub fn mean(xs: &[f64]) -> Option<f64> {
if xs.is_empty() {
return None;
}
Some(xs.iter().sum::<f64>() / xs.len() as f64)
}
RS
echo 'fn main() { println!("example: mean = {:?}", stats::mean(&[2.0, 4.0, 9.0])); }' > examples/demo.rs
cat > src/bin/mean.rs <<'RS'
fn main() {
let xs: Vec<f64> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
println!("{:?}", stats::mean(&xs));
}
RS
cat > tests/api.rs <<'RS'
#[test]
fn mean_of_two() {
assert_eq!(stats::mean(&[1.0, 4.0]), Some(2.5));
}
RS
cat > benches/speed.rs <<'RS'
use std::hint::black_box;
// harness = false: this file is a plain program. A real benchmark harness
// (criterion, divan) would time many iterations and report statistics.
fn main() {
let xs: Vec<f64> = (0..1_000_000).map(|i| i as f64).collect();
let mut m = None;
for _ in 0..100 {
m = stats::mean(black_box(&xs));
}
println!("bench: mean of 1e6 values = {m:?}");
}
RS
cat >> Cargo.toml <<'T'
[[bench]]
name = "speed"
harness = false
T
cargo run -q --bin mean -- 1 2 3 4
cargo run -q --example demo
cargo test -q 2>&1 | grep -E 'running|test result'
cargo bench -q 2>&1 | grep -v -e '^