๐ŸŽ“ A1Learner
๐Ÿ”

Rust Project Layout

Project layout is the standard arrangement of files in a Cargo project. Cargo decides what to build from where a file sits, and a standard layout needs almost no configuration.

The default pair

Most packages hold these two files. The program takes the name of the package. The library is the same package's reusable half.

src/main.rs   the default binary โ€” cargo run starts it
src/lib.rs    the library

Extra programs live in src/bin

Every file there becomes its own binary, named by its file name. With several binaries, a plain cargo run stops and asks you to choose. This was checked in a scratch project. Cargo lists the available binaries there.

src/bin/tool.rs
cargo run --bin tool

Examples show the library in use

Small demo programs live in examples/. They are not part of the program you ship.

examples/demo.rs
cargo run --example demo

Tests and benchmarks have their folders

Cargo finds them by folder: cargo test runs the integration tests, cargo bench runs the benchmarks.

tests/name.rs
benches/name.rs

One special file in the root

build.rs sits next to Cargo.toml. Cargo runs it before building your package โ€” the next lesson is all about it.

build.rs

Example

fn main() {
    println!("src/main.rs -> the default binary");
    println!("src/lib.rs -> the library");
    println!("src/bin/tool.rs -> binary tool: cargo run --bin tool");
    println!("examples/demo.rs -> example demo: cargo run --example demo");
    println!("tests/ and benches/ -> cargo test and cargo bench");
}

Key points

  • Folders do the configuring.
  • Only a target with a special name or path needs more.
  • It needs a [[bin]] or [lib] section in Cargo.toml
  • Use cargo run --bin name to run one chosen binary.
  • With several binaries and no --bin, cargo run stops and asks you to choose.
  • cargo build still builds them all

In this example, the program prints the layout map, one target per line. The first two lines are the pair most packages have: src/main.rs for the program and src/lib.rs for the library. The third line adds a second program in src/bin, run with --bin tool. The fourth line is an example program, run with --example demo. The last line names the two folders Cargo searches by name: tests/ for cargo test and benches/ for cargo bench.

Note

This is called convention over configuration.

The same layout in every Rust project puts everything in a familiar place.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Rust Playground

Exercise

You add a second program in src/bin/report.rs. How do you run only that program?