Sub topic 7
Library and Binary Crates in One Package
This chapter assumes you can read basic Rust, run cargo build and cargo run, and know that a module tree starts at a crate root. It covers how one Cargo package can hold a library crate and one or more binary crates, and why that layout is the usual way to make a program testable.
One package, several crates
A package is what a Cargo.toml describes. A crate is one compilation unit. A package can contain:
- at most one library crate,
- any number of binary crates,
- examples, tests, and benchmarks, each of which is also compiled as its own crate.
Cargo finds the crates by convention, so you rarely have to configure anything.
| File | Crate it defines | Crate name |
|---|---|---|
| `src/lib.rs` | The library crate root | The package name (hyphens become underscores) |
| `src/main.rs` | The default binary crate root | The package name |
| `src/bin/tool.rs` | An extra binary | `tool` |
| `src/bin/tool/main.rs` | An extra binary split over several files | `tool` |
If both src/lib.rs and src/main.rs exist, the package builds two crates with the same name. cargo build builds both, and cargo run runs the binary.
Why split a program into a library and a binary
A binary crate has no public API. Nothing can use it, so integration tests in tests/ cannot import its functions. A library crate can be imported by tests, by other binaries in the package, and by other packages.
The common pattern is to keep main.rs very small. It parses arguments, calls into the library, and turns errors into an exit code. All logic lives in the library, where it can be tested.
A worked example
Create a package named wordcount:
cargo new wordcountCargo generates src/main.rs. Add a src/lib.rs next to it. The library holds the logic:
// src/lib.rs
use std::collections::BTreeMap;
/// Counts how often each word appears, ignoring case.
pub fn count_words(text: &str) -> BTreeMap<String, usize> {
let mut counts = BTreeMap::new();
for word in text.split_whitespace() {
*counts.entry(word.to_lowercase()).or_insert(0) += 1;
}
counts
}
/// Formats counts as one `word: n` line each.
pub fn render(counts: &BTreeMap<String, usize>) -> String {
counts
.iter()
.map(|(word, n)| format!("{word}: {n}"))
.collect::<Vec<_>>()
.join("\n")
}The binary imports the library by the package name:
// src/main.rs
use std::io::Read;
use std::process;
use wordcount::{count_words, render};
fn main() {
let mut input = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut input) {
eprintln!("error reading input: {e}");
process::exit(1);
}
let counts = count_words(&input);
println!("{}", render(&counts));
}Run it with piped input:
echo "the cat and The dog" | cargo runThe output is:
and: 1
cat: 1
dog: 1
the: 2Inside main.rs, wordcount is an external crate, exactly like a dependency. Cargo adds it automatically. You do not list it in [dependencies]. This also means main.rs can only use items marked pub in lib.rs. Privacy rules apply between the two crates.
Multiple binaries
Files in src/bin/ each become a separate binary. They all share the library.
wordcount/
├── Cargo.toml
├── src/
│ ├── lib.rs
│ ├── main.rs
│ └── bin/
│ └── unique.rs
└── tests/Choose which binary to run with --bin:
cargo run --bin unique
cargo run --bin wordcountIf a package has several binaries and no default, cargo run asks you to pick one. You can set a default in the manifest:
[package]
name = "wordcount"
version = "0.1.0"
edition = "2021"
default-run = "wordcount"Customizing crate targets in Cargo.toml
You can override the conventions with [lib] and [[bin]] tables. The double brackets mark a TOML array of tables, because there can be many binaries.
[package]
name = "wordcount"
version = "0.1.0"
edition = "2021"
[lib]
name = "wordcount_core"
path = "src/core.rs"
[[bin]]
name = "wc"
path = "src/cli.rs"With this manifest the library is imported as wordcount_core, and the binary is installed as wc. Use this when the library name and the command name should differ. Otherwise, keep the defaults, because other developers expect them.
Setting [lib] or [[bin]] does not disable auto-discovery of other files. If you add autobins = false to [package], Cargo stops scanning src/bin/, and you must list every binary yourself.
Testing the split
The split pays off for testing. The tests/ directory can call the library but cannot call code in main.rs:
// tests/counts.rs
use wordcount::{count_words, render};
#[test]
fn counts_ignore_case() {
let counts = count_words("Rust rust RUST");
assert_eq!(counts["rust"], 3);
}
#[test]
fn render_is_sorted_by_word() {
let counts = count_words("b a b");
assert_eq!(render(&counts), "a: 1\nb: 2");
}Run only this file with cargo test --test counts. Unit tests inside lib.rs still work as before, since they live in a #[cfg(test)] module inside the library crate.
A binary-only package can still hold unit tests inside main.rs. Doc tests, however, only run for library crates. If your package has no lib.rs, cargo test --doc has nothing to check.
Common errors and gotchas
unresolved import wordcountinmain.rs. The package has nosrc/lib.rs, or the[lib]table renamed the library. Check the library name.function is privatewhen calling frommain.rs. The library function lackspub. The binary is a separate crate, so private items are invisible to it.- Hyphens in package names. A package named
word-countproduces a crate namedword_count. Cargo converts the hyphen, and you writeuse word_count::.... - Declaring modules twice. Write
mod counter;inlib.rsonly. Ifmain.rsalso saysmod counter;, the binary compiles its own private copy of that module. The result is duplicated code and types that do not match the library's types. Useuse wordcount::counter;instead. - Dependencies are shared. Both crates read the same
[dependencies]table. A library-only dependency still gets linked into the binary if the binary uses the library. You cannot give the binary a separate dependency list within one package. If you need that, split into a workspace with two packages. - Doc tests are slow to notice. Because they only run for libraries, a logic-heavy
main.rsgets no doc-test coverage.
Choosing a layout
| Situation | Layout |
|---|---|
| Small script, no tests beyond unit tests | `main.rs` only |
| A program you want integration tests for | `lib.rs` for logic, thin `main.rs` |
| A library that also ships a helper command | `lib.rs` plus `src/bin/` |
| A command line tool whose parts need separate dependency lists or versions | A workspace with several packages |
Start with main.rs. When you want to write an integration test, or a second binary needs the same code, move the logic to lib.rs and keep main.rs as a thin wrapper.
Exercise
A package named log-tool has both src/lib.rs and src/main.rs. In main.rs, you write mod parser; and also have pub mod parser; in lib.rs, with src/parser.rs present. Integration tests in tests/ call log_tool::parser::parse. Later you find that a Token value returned by parse cannot be passed to a function in main.rs that takes parser::Token. Why does this happen, and how do you fix it?
Show answer
The mod parser; line in main.rs makes the binary crate compile its own separate copy of src/parser.rs, so parser::Token in the binary is a different type from log_tool::parser::Token in the library. Remove mod parser; from main.rs and import the library's module with use log_tool::parser;. The crate name uses an underscore because Cargo converts the hyphen in the package name.
Exercise
You want a package to build a library and two commands, serve and migrate, with serve as the one cargo run starts by default. Which files do you create, and what do you add to Cargo.toml?
Show answer
Create src/lib.rs, src/bin/serve.rs, and src/bin/migrate.rs. Add default-run = "serve" to the [package] table. Then cargo run starts serve, and cargo run --bin migrate starts the other command.