23.10 Binary vs. Library Crates

Cargo distinguishes between two primary types of crates:

  • Binary Crates: Compile to an executable file. They must have a src/main.rs file containing a fn main() function, which serves as the program’s entry point. cargo new <name> creates a binary crate by default.
  • Library Crates: Compile to a Rust library file (.rlib or .dylib) intended to be used as a dependency by other crates. They typically have a src/lib.rs file as their crate root. cargo new <name> --lib creates a library crate.

A single package can contain both a library and one or more binaries:

  • Define the library in src/lib.rs.
  • Define the main binary in src/main.rs.
  • Define additional binaries in src/bin/another_bin.rs, src/bin/yet_another.rs, etc.

Cargo will build the library and all specified binaries. This pattern is common for crates that provide both a reusable library API and a command-line tool interface.