Sub topic 7
Enabling and disabling crate features
This chapter assumes you can add a dependency with cargo add or by editing [dependencies]. It also assumes you can read a SemVer requirement such as "1". You should be able to build a small project with cargo build.
Many crates ship more code than any one project needs. Features let you choose which parts to compile. Here you will enable features, turn off defaults, predict how Cargo combines feature requests, and inspect the result.
What a feature is
A feature is a named switch that a crate author defines. Turning it on compiles extra code or pulls in extra dependencies. Turning it off leaves that code out of your build.
Features serve three common purposes:
- Optional functionality.
serdehides its derive macros behind a feature calledderive. - Smaller builds.
tokiosplits its runtime, networking, timers and other parts into separate features. - Integration with other crates. A crate may offer a
serdefeature that addsSerializeimplementations only when you ask.
Features are part of a crate's public interface, and the crate's documentation lists them. On docs.rs, the "Feature flags" page for a crate shows each feature and what it enables.
Enabling features
You can enable features with cargo add:
cargo add serde --features derive
cargo add serde_json --features preserve_orderThe short flag -F does the same job as --features. Separate several features with commas: cargo add tokio -F rt,macros.
cargo add writes the result into Cargo.toml. You can also write it by hand using the table form of a dependency:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }If you forget a needed feature, the error appears when you use the item, not when you add the dependency. Without derive, this code fails to compile:
use serde::Serialize;
#[derive(Serialize)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{}", p.x + p.y);
}The compiler reports that it cannot find the derive macro Serialize in this scope. The fix is to add features = ["derive"]. Treat "cannot find X in this scope" for something the documentation says exists as a hint to check the feature list.
Default features and turning them off
Most crates define a feature called default. It is a list of other features that Cargo enables automatically when you do not say otherwise. For example, tokio has no default features that would give you a runtime, but many crates do enable several defaults.
To avoid the defaults, set default-features = false. Then list only the features you need:
[dependencies]
tokio = { version = "1", default-features = false, features = ["rt", "macros"] }The command-line equivalent is:
cargo add tokio --no-default-features --features rt,macrosWith that dependency, this program compiles and runs:
#[tokio::main(flavor = "current_thread")]
async fn main() {
println!("hello from a single-threaded runtime");
}The macros feature provides #[tokio::main]. The rt feature provides the single-threaded runtime that the current_thread flavor uses. If you remove either feature, the build fails.
Turning off defaults helps in three cases:
- You want a smaller binary or faster compile times.
- You target an environment that lacks something a default feature needs, such as an operating system or a
stdlibrary. - You want to know exactly which code you pull in.
The cost is that you must read the crate's feature list and name what you need. A feature that was on by default may be required by something you use.
Features are additive
Cargo assumes that turning on a feature never breaks code that worked without it. Features should only add items and never remove or change them. Because of that rule, Cargo can safely merge feature requests from different places. This leads to feature unification.
Feature unification
Suppose your project depends on tokio with rt and macros. Another crate in your dependency tree also depends on the same tokio version, with net and time. Cargo builds tokio once, with the union of all requested features: rt, macros, net and time.
This has practical consequences:
- Setting
default-features = falsein your manifest does not guarantee defaults are off. If any other crate in the graph requests the defaults, they get enabled for everyone. - A feature can be enabled in your build even though you never asked for it. A transitive dependency may have enabled it.
- Code that compiles in your project may fail when someone else uses it with a different set of dependencies, if you rely on a feature you did not declare. Always declare the features you use directly.
Unification applies per crate version. If your tree contains rand 0.7 and rand 0.8, each is built separately with its own merged features.
Resolver versions
The resolver is the part of Cargo that picks versions and merges features. The original resolver (version 1) unified features across normal dependencies, build dependencies, dev dependencies and platform-specific dependencies. This could turn on features for your release build that only a test needed.
Resolver version 2 keeps those groups separate when it can. It is the default for packages using edition 2021 or later. In a workspace with only a virtual manifest (a root Cargo.toml that has no [package]), you must set it yourself:
[workspace]
members = ["app", "util"]
resolver = "2"Inspecting enabled features
When a feature is on and you do not know why, ask Cargo:
cargo tree -e features
cargo tree -e features -i tokioThe first command adds feature nodes to the dependency tree, so you can see which package enabled which feature. The second command uses -i (inverted) to show what pulls in tokio, including the feature edges. You can narrow the output to one package. For example, cargo tree -e features -p tokio shows the features enabled for tokio and what they bring in.
To see what the compiler actually received, build with verbose output. Each rustc invocation lists --cfg 'feature="..."' flags for the crate it compiles:
cargo build -vDefining features in your own crate
You will eventually publish a crate or a library inside a workspace. Defining features shows you how consumers experience them. Features are declared in a [features] table. An optional dependency becomes a feature that you expose under your own name with the dep: prefix:
[package]
name = "textkit"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[features]
default = []
serde = ["dep:serde"]In src/lib.rs, code is compiled only when the feature is on:
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Token {
pub text: String,
}Anyone depending on textkit gets no serde code unless they write features = ["serde"]. You can test your own feature set from the command line:
cargo build --features serde
cargo build --no-default-features
cargo build --all-featuresCheck at least the default set, no features and all features in CI. A combination that was never built is a common source of broken releases.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `cannot find derive macro` or `unresolved import` for an item the docs show | The feature that gates it is off | Add it to `features` |
| Build fails after `default-features = false` | A default feature provided something you use | Re-enable the needed feature by name |
| A feature you did not request is on | Another crate enabled it, so unification merged it | Run `cargo tree -e features -i <crate>` to find the source |
| `package does not have feature` error | Typo, or the feature exists only in a newer version | Check the crate's docs for that exact version |
| Different features in tests than in release | Resolver 1 unified dev and normal dependencies | Use edition 2021 or set `resolver = "2"` |
Exercise
Your project depends on tokio = { version = "1", default-features = false, features = ["rt"] }. Another dependency in the same tree requires tokio = "1" with its default features. Which tokio features are compiled, and which command shows who enabled them?
Show answer
Cargo unifies the requests and builds tokio once. It compiles rt plus every feature in tokio's default set, because the other dependency requested the defaults and default-features = false in your manifest cannot override that. Run cargo tree -e features -i tokio to see which package enabled each feature.
Exercise
You run cargo add serde_json --no-default-features and the build then fails with a message about a missing std item. What is the most likely cause, and what are two ways to fix it?
Show answer
A default feature, probably std, provided what your code needs. You can fix it by re-enabling it with cargo add serde_json --features std, or by removing --no-default-features and going back to the defaults. Check the crate's feature list to confirm the name.
Exercise
A library you maintain has an optional dependency regex. Write the two Cargo.toml entries that make it available to users under a feature named search, and the command that builds with it.
Show answer
Under [dependencies] write regex = { version = "1", optional = true }. Under [features] write search = ["dep:regex"]. Build with cargo build --features search.