Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 132 ยท Modules, Packages and Macros

Crates, Dependencies and Features

Understand Rust crates: library vs binary crates, Cargo.toml dependencies, semver, features, workspaces, build.rs, publishing to crates.io and key ecosystem crates.

A crate is the unit of compilation in Rust: one run of rustc turns one crate into either an executable or a library. Everything you have written so far has been a single binary crate whose root is main.rs. The real power of the language comes from the fact that crates can depend on other crates, and that there is a public registry, crates.io, with well over a hundred thousand of them, from JSON parsers to web servers to game engines. Adding one is a line in a text file.

This lesson is about that world: what the words crate, package and workspace mean, how a library crate differs from a binary, how Cargo.toml describes dependencies, how semantic versioning keeps upgrades safe, how features switch optional parts on and off, what build.rs is for, how publishing works and which crates almost every Rust programmer meets. One important limitation first: our in-browser editor compiles a single file with only the standard library, so Cargo, Cargo.toml and external crates cannot run here. The Cargo.toml and shell snippets below are read-only, and wherever an idea can be demonstrated in plain Rust, there is a runnable example next to it.

Packages, crates and modules: the vocabulary

People mix up these terms. Here is the hierarchy, from smallest to largest:

  • A module organizes code inside a crate (see modules).
  • A crate is a tree of modules compiled together. It is either a binary crate (has fn main, produces an executable) or a library crate (no main, produces a reusable .rlib).
  • A package is what Cargo manages: a folder with a Cargo.toml that contains at most one library crate and any number of binary crates.
  • A workspace is a set of packages developed together that share one Cargo.lock and one build directory.

By convention, Cargo finds the crates by file location, so you rarely configure it:

TEXT
my_tool/
โ”œโ”€โ”€ Cargo.toml
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs          // the library crate (named after the package)
โ”‚   โ”œโ”€โ”€ main.rs         // the default binary crate
โ”‚   โ””โ”€โ”€ bin/
โ”‚       โ””โ”€โ”€ extra.rs    // another binary: cargo run --bin extra
โ”œโ”€โ”€ tests/              // integration tests, each file is its own crate
โ”œโ”€โ”€ examples/           // runnable examples: cargo run --example demo
โ””โ”€โ”€ benches/            // benchmarks

Library crate versus binary crate

Why would a package contain both lib.rs and main.rs? Because it is a very good habit: keep the real logic in the library, which tests and other programs can use, and make main.rs a thin wrapper that parses arguments, calls the library, and turns the result into an exit code. Our single file can model the shape with an inline module standing in for the library:

Rust A thin binary over a library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In a real package, main.rs would say use my_tool::wordstats; (the library is named after the package) and the integration tests in tests/ could call summarize directly, with no process to spawn and no output to capture.

Dependencies in Cargo.toml

Cargo.toml is the manifest. Its [package] table names the crate and sets the edition; the [dependencies] table lists what you need. The following is read-only (our editor cannot fetch crates):

TOML
[package]
name = "my_tool"
version = "0.3.1"
edition = "2024"
rust-version = "1.85"      # the oldest compiler you promise to support (MSRV)

[dependencies]
serde = { version = "1", features = ["derive"] }   # with a feature switched on
regex = "1"                                        # shorthand for version = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
local_helper = { path = "../local_helper" }        # a sibling folder
fancy = { git = "https://example.com/fancy.git", rev = "a1b2c3d" }
clock = { version = "0.4", optional = true }       # only built if a feature asks

[dev-dependencies]          # used by tests, examples and benchmarks only
pretty_assertions = "1"

[build-dependencies]        # used by build.rs only
cc = "1"

From the command line you rarely edit this by hand:

Terminal
cargo add serde --features derive   # adds the line for you
cargo add --dev pretty_assertions
cargo remove regex
cargo tree                          # shows the whole dependency tree
cargo update                        # moves Cargo.lock to the newest compatible versions

Once a crate is listed you use it by name with a normal use path, exactly like std:

Rust
// Read-only: needs the regex crate in Cargo.toml
use regex::Regex;

fn main() {
    let re = Regex::new(r"\d{4}-\d{2}-\d{2}").unwrap();
    println!("{}", re.is_match("released on 2025-02-20"));
}

If you paste code like that into our editor, the compiler does what it should when a crate is missing:

Rust Using a crate the editor does not have (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc reports E0432 ("unresolved import rand") for the use line and E0433 for the rand::rng() call, both with the help "you might be missing a crate named rand". The fix in a real project is cargo add rand; here, you would write a tiny generator by hand, as many lessons in this tutorial do.

Semantic versioning and what Cargo does with it

Crate versions follow semver: MAJOR.MINOR.PATCH. The promise is:

  • PATCH (1.4.2 to 1.4.3): bug fixes only, nothing observable breaks.
  • MINOR (1.4.2 to 1.5.0): new features, still backward compatible.
  • MAJOR (1.4.2 to 2.0.0): breaking changes allowed.

A plain version in Cargo.toml such as "1.4.2" is shorthand for a caret requirement ^1.4.2, meaning "any version that is semver-compatible with 1.4.2, but at least that": >=1.4.2, <2.0.0. Cargo picks the newest matching version when it resolves, and writes the exact choice into Cargo.lock. For binaries, commit the lock file, so every build uses the same versions; libraries traditionally do not need to, because their users' own lock file decides.

Versions below 1.0 are special: for 0.x.y the minor number acts as the major one, so ^0.4.2 means >=0.4.2, <0.5.0, and ^0.0.3 allows only 0.0.3.

To make the rule concrete, here is a small, runnable checker for caret requirements:

Rust How a caret requirement decides compatibility

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the three lines of output: ^1.4.2 takes anything from 1.4.2 up to (not including) 2.0.0; ^0.4.2 stops before 0.5.0; and ^0.0.3 accepts exactly one version. Real Cargo also supports =1.4.2 (exact), ~1.4.2 (patch updates only), wildcards 1.* and ranges >=1.2, <1.5, but the plain caret form is right almost every time.

Two different versions of a crate can coexist in one build when they are semver-incompatible (for example rand 0.7 pulled in by one dependency and rand 0.9 by another). Types from the two versions are unrelated, and passing one where the other is expected gives confusing errors. cargo tree --duplicates shows when this happens.

Features: optional parts of a crate

A feature is a named compile-time switch declared by a crate. It enables optional code and, usually, optional dependencies. Crates use features to keep the default build small: serde has a derive feature, tokio has dozens, reqwest has json and blocking. In the crate's own manifest:

TOML
# Read-only: the manifest of a hypothetical library crate
[features]
default = ["std"]          # on unless the user disables default features
std = []
json = ["dep:serde_json"]  # turns on an optional dependency
fast-math = []

[dependencies]
serde_json = { version = "1", optional = true }

and in its source code the switches become cfg conditions:

Rust
// Read-only: needs the feature to be declared in Cargo.toml
#[cfg(feature = "json")]
pub fn to_json(value: &Report) -> String {
    serde_json::to_string(value).unwrap()
}

pub fn describe() -> &'static str {
    if cfg!(feature = "fast-math") { "fast" } else { "exact" }
}

A user picks features when adding the dependency: my_lib = { version = "1", default-features = false, features = ["json"] }. The rule that matters most is that features are additive. Cargo builds each crate once per build, with the union of every feature any dependent asked for. So a feature must never remove functionality or change what existing functions mean; it may only add. A "no-std" mode, for example, is written as std being a feature that adds things, not no_std being a feature that removes them.

Single-file code can still use the same cfg machinery with the conditions rustc defines on its own, like debug mode or the target platform:

Rust Built-in cfg conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

#[cfg(...)] removes the item from the program before type checking, so code in the disabled branch may even refer to things that do not exist on this platform. cfg!(...) is an ordinary expression that evaluates to true or false, but both branches still have to compile. Features work through exactly this mechanism, with feature = "name" as the condition; you will see more in attributes and cfg.

Edition 2024 packages use feature resolver 3 by default (also called the MSRV-aware resolver, stable since Rust 1.84), which prefers dependency versions that work with the rust-version declared in your manifest instead of blindly picking the newest ones.

Workspaces

When a project grows into several crates (a core library, a command-line front end, a server), put them in a workspace: a root manifest that lists the members. They share one Cargo.lock and one target/ folder, so common dependencies are compiled once, and cargo test --workspace tests everything. Read-only layout:

TOML
# Cargo.toml at the workspace root
[workspace]
resolver = "3"
members = ["crates/core", "crates/cli", "crates/server"]

[workspace.package]            # values members can inherit
version = "0.3.1"
edition = "2024"

[workspace.dependencies]       # one place to pin versions
serde = { version = "1", features = ["derive"] }
TOML
# crates/cli/Cargo.toml
[package]
name = "cli"
version.workspace = true
edition.workspace = true

[dependencies]
serde.workspace = true         # inherits version and features
core = { path = "../core" }    # a sibling in the same workspace

Cargo forbids dependency cycles: package A may not depend on B if B depends on A. It must be able to compile dependencies before dependents, which means ordering the packages. This runnable sketch does what Cargo does, a depth-first topological sort with cycle detection:

Rust Build order and cycle detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In the first run every package appears after the packages it depends on, which is exactly the order in which Cargo compiles. The second run reports a cycle, the same situation that makes Cargo stop with cyclic package dependency.

build.rs: code that runs before your code

If a file named build.rs sits next to Cargo.toml, Cargo compiles and runs it before building the crate. A build script can compile C code (the cc crate), generate Rust source into the output folder, detect the platform, or tell Cargo to link a system library. It talks to Cargo by printing lines starting with cargo::. Read-only:

Rust
// Read-only: build.rs
fn main() {
    // Re-run this script only when the schema changes.
    println!("cargo::rerun-if-changed=schema.json");
    // Expose a value to the crate as env!("BUILD_PROFILE").
    let profile = std::env::var("PROFILE").unwrap();
    println!("cargo::rustc-env=BUILD_PROFILE={profile}");
}

Use build scripts sparingly: they slow every clean build, they run arbitrary code at compile time (a security consideration for anything you depend on) and they complicate cross-compilation. Reach for ordinary code, macros or features first.

Publishing to crates.io

Sharing a library is a handful of commands (all read-only here, and they need an account and a token):

Terminal
cargo login                    # paste an API token from crates.io
cargo package --list           # which files would be uploaded
cargo publish --dry-run        # everything except the upload
cargo publish                  # permanent!
cargo yank --version 0.3.1     # discourage new users from picking a bad release

The manifest needs description, license (an SPDX string such as "MIT OR Apache-2.0", the most common dual license in the ecosystem) and usually repository, readme and keywords. Remember that publishing is permanent: a version cannot be changed or deleted, only yanked, which stops new projects from selecting it while existing lock files keep working. Public APIs are promises, so follow semver strictly, write doc comments (they become the page on docs.rs, generated automatically for every published crate), and run cargo semver-checks if you want a tool to catch accidental breaking changes.

A short tour of the ecosystem

The standard library is deliberately small; many things you may expect to be built in come from crates. These are widely used, so you will meet them early (check crates.io for current versions and details):

Area Crate What it does
Serialization serde (+ serde_json, toml) Derive Serialize / Deserialize and convert to and from JSON, TOML, and more
Async runtime tokio Executor, timers, networking, tasks (see the async lessons)
Command line clap Argument parsing from a derive on a struct
Data parallelism rayon Turn .iter() into .par_iter() for multi-core loops
Errors thiserror, anyhow Boilerplate-free error enums; flexible application errors (custom errors)
Text regex Fast regular expressions without catastrophic backtracking
Randomness rand Random numbers and distributions (the standard library has none)
Time chrono, time Calendars, time zones, formatting
HTTP reqwest, axum, hyper Client, web framework, and the low-level engine under both
Logging tracing, log Structured, leveled diagnostics
Databases sqlx, diesel, rusqlite SQL access
Testing proptest, criterion Property-based tests; statistical benchmarks

Before adding any dependency, ask the questions experienced developers ask: Is it maintained? How many dependencies does it bring (cargo tree)? Is the license compatible with yours? Could 20 lines of your own code do the job? Every dependency is code you ship and trust. Tools like cargo audit (known vulnerabilities) and cargo deny (licenses, duplicates, bans) automate part of that checking.

A good habit: cargo add only what you need, turn off default features when you only need a slice of a big crate (default-features = false), and commit Cargo.lock for every application.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many library crates can one Cargo package contain?

    A package has at most one library crate (src/lib.rs) and any number of binary crates.
  2. 2. What does the dependency line serde = "1.4.2" allow Cargo to select?

    A bare version is a caret requirement: ^1.4.2 means >=1.4.2, <2.0.0.
  3. 3. Why must Cargo features be additive?

    Different dependents may ask for different features, but the crate is built once with all of them on, so a feature must never break code that expects it to be off.
  4. 4. What is the purpose of Cargo.lock?

    The lock file pins every resolved version. Applications should commit it.
  5. 5. Which statement about publishing to crates.io is true?

    Yanking prevents new projects from depending on a version, but the code stays available so existing lock files keep working.

Summary

  • A crate is one compilation unit (binary or library); a package has a Cargo.toml with at most one library and any number of binaries; a workspace groups packages that share a lock file and build folder.
  • Keep logic in the library crate and make main.rs a thin wrapper, so it can be tested and reused.
  • [dependencies] entries can come from crates.io, a path or git, can be optional, and have dev and build variants; cargo add, cargo tree and cargo update manage them.
  • A plain version means a caret requirement under semver (with 0.x treating the minor number as the breaking one); Cargo.lock pins what was chosen.
  • Features are additive compile-time switches built on cfg; edition 2024 uses the MSRV-aware resolver 3.
  • build.rs runs before compilation; use it sparingly. Publishing to crates.io is permanent, so follow semver.
  • Our editor runs one file with only std, so external crates are read-only here; the ecosystem tour lists what to reach for in real projects.

Next: Declarative Macros (macro_rules!)