TExcelTAD
Home › Cargo in Depth › Targets: bins, examples, tests & benches

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 '^
  

 -e 'running 0' -e '0 passed'
echo "--- build every target"
cargo build --all-targets 2>&1 | tail -1
ls target/debug/examples | grep -v '\.d
  

 | grep -v -- '-'
Some(2.5)
example: mean = Some(5.0)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 1 test
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
bench: mean of 1e6 values = Some(499999.5)
--- build every target
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s
demo
  • cargo test also built the example (so a broken example fails CI) but didn't run it.
  • cargo bench uses the bench profile (optimised). The built-in #[bench] attribute is nightly-only, so on stable you set harness = false and provide your own main, usually through a crate like criterion or divan, which handle warm-up, statistics and comparison with earlier runs.
  • --all-targets builds lib, bins, examples, tests and benches in one go. It's what cargo check --all-targets and cargo clippy --all-targets in CI should use.

Configuring targets explicitly

Each kind has a table. [lib] appears once; the others are arrays ([[bin]]), one entry per target:

toml
[lib]
name = "stats"                 # crate name in code (default: package name with - → _)
path = "src/lib.rs"
crate-type = ["lib", "cdylib"] # also build a C-compatible shared library
doctest = true

[[bin]]
name = "stats-server"
path = "src/bin/server.rs"
required-features = ["server"] # skipped unless the feature is on

[[example]]
name = "plot"
required-features = ["plotting"]

[[test]]
name = "slow"
harness = true

[[bench]]
name = "speed"
harness = false

required-features deserves a closer look: it lets a package ship a binary or example that needs optional dependencies without forcing them on library users.

bash · try it yourself
cargo new --lib stats --vcs none -q
cd stats
mkdir -p src/bin
echo 'pub fn mean(xs: &[f64]) -> f64 { xs.iter().sum::<f64>() / xs.len() as f64 }' > src/lib.rs
cat > src/bin/stats-json.rs <<'RS'
fn main() {
    let m = stats::mean(&[1.0, 2.0, 6.0]);
    println!("{}", serde_json::json!({ "mean": m }));
}
RS
cat >> Cargo.toml <<'T'
serde_json = { version = "1", optional = true }

[features]
cli = ["dep:serde_json"]

[[bin]]
name = "stats-json"
required-features = ["cli"]
T
cargo build -q 2>&1
ls target/debug | grep stats-json || echo "no stats-json binary"
cargo run -q --bin stats-json 2>&1
cargo run -q --bin stats-json --features cli 2>&1 | grep -v Unpacking
no stats-json binary
error: target `stats-json` in package `stats` requires the features: `cli`
Consider enabling them by passing, e.g., `--features="cli"`
{"mean":3.0}

Auto-discovery switches

Listing a target explicitly doesn't turn discovery off for the others. If a folder like examples/ contains files that aren't targets (data, helper modules), switch discovery off for that kind with autoexamples = false (also autobins, autotests, autobenches, autolib) in [package]. Helper code shared by integration tests goes in tests/common/mod.rs: a folder without main.rs is not a test target.

Test yourself

What does cargo test do with files in examples/?

  1. Ignores them
  2. Builds them (so they must compile) but doesn't run them
  3. Runs them as tests
  4. Runs them after the tests

Why does benches/speed.rs have harness = false on stable Rust?

  1. To run in debug mode
  2. The built-in #[bench] harness is nightly-only, so the file provides its own main (often via criterion or divan)
  3. Benches can't use the library otherwise
  4. To skip it in CI

A binary needs serde_json, which library users shouldn't pay for. What's the idiomatic setup?

  1. Put serde_json in [dependencies]
  2. Make serde_json optional behind a feature and give the [[bin]] required-features
  3. Move the binary to examples/
  4. Use a build script