TExcelTAD
Home › Cargo in Depth › Features: default, dep: and ?

Features: default, dep: and ?

Features are named switches in Cargo.toml that turn on optional code (through #[cfg(feature = "...")]) and optional dependencies. They let one crate serve users who want a tiny core and users who want serde support, async, SIMD or a CLI. Cargo's design has one strict assumption behind it, covered in the next lesson: features only add things.

Declaring features

toml
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
palette = { path = "../palette", optional = true }   # a local crate of colour schemes

[features]
default = ["names"]                  # what users get unless they opt out
names = []                           # a plain switch: only enables cfg(feature = "names")
hex = []
palettes = ["dep:palette"]                # turns on the optional dependency palette
serde = ["dep:serde", "palette?/serde"] # serde support, also for palette IF palette is on
full = ["hex", "palettes", "serde"]    # a feature can enable other features
Syntax Meaning
name = [] a feature that only sets cfg(feature = "name")
"other" enable another feature of this crate
"dep:palette" enable the optional dependency palette without creating a feature called palette
"palette/serde" enable feature serde of dependency palette (and enable palette itself if it's optional)
"palette?/serde" weak: enable palette's serde feature only if palette is enabled by something else
default = [...] features on by default

Implicit features. Without any dep: mention, every optional dependency silently becomes a feature with its own name (--features palette). As soon as one dep:palette appears, that implicit feature is gone. Prefer dep:: it keeps dependency names out of your public feature list, so you can swap a dependency later without a breaking change.

Using features in code

rust
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Rgb(pub u8, pub u8, pub u8);

#[cfg(feature = "hex")]
pub fn to_hex(c: &Rgb) -> String { format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2) }

Code behind a disabled feature isn't compiled at all, so it can't slow the build or bloat the binary. It also isn't type-checked, which is why CI should build more than the default feature set.

Choosing features from the command line

Flag Effect
--features hex,serde (or -F) enable these, in addition to default
--no-default-features turn default off
--all-features everything (useful for cargo doc and clippy)
-F color/hex a feature of a specific workspace member
bash · try it yourself
cargo new --lib palette --vcs none -q
printf '\n[features]\nserde = []\n' >> palette/Cargo.toml
cargo new --lib color --vcs none -q
cd color
cat >> Cargo.toml <<'T'
palette = { path = "../palette", optional = true }
serde = { version = "1", features = ["derive"], optional = true }

[features]
default = ["names"]
names = []
hex = []
palettes = ["dep:palette"]
serde = ["dep:serde", "palette?/serde"]
T
mkdir -p examples
cat > src/lib.rs <<'RS'
pub struct Rgb(pub u8, pub u8, pub u8);

pub fn describe(c: &Rgb) -> String {
    let mut out = format!("rgb({}, {}, {})", c.0, c.1, c.2);
    if cfg!(feature = "names") && (c.0, c.1, c.2) == (255, 0, 0) {
        out.push_str(" = red");
    }
    if cfg!(feature = "hex") {
        out.push_str(&format!(" = #{:02x}{:02x}{:02x}", c.0, c.1, c.2));
    }
    out
}
RS
echo 'fn main() { println!("{}", color::describe(&color::Rgb(255, 0, 0))); }' > examples/show.rs
cargo run -q --example show
cargo run -q --example show --features hex
cargo run -q --example show --no-default-features
cargo run -q --example show --all-features 2>&1 | grep -v -e Unpacking
rgb(255, 0, 0) = red
rgb(255, 0, 0) = red = #ff0000
rgb(255, 0, 0)
rgb(255, 0, 0) = red = #ff0000

--all-features also compiled palette and serde (that's why it took longer); the example didn't use them, but every enabled optional dependency is built.

Seeing what a feature turns on

cargo tree -e features adds feature nodes to the graph. The weak palette?/serde is easiest to understand by watching it:

bash · try it yourself
cargo new --lib palette --vcs none -q
printf '\n[features]\nserde = []\n' >> palette/Cargo.toml
cargo new --lib color --vcs none -q
cd color
cat >> Cargo.toml <<'T'
palette = { path = "../palette", optional = true }
serde = { version = "1", features = ["derive"], optional = true }

[features]
palettes = ["dep:palette"]
serde = ["dep:serde", "palette?/serde"]
T
cargo fetch -q
echo "--- --features serde"
cargo tree -e features --features serde -i palette 2>&1
echo "--- --features serde,palettes"
cargo tree -e features --features serde,palettes -i palette
--- --features serde
warning: nothing to print.

To find dependencies that require specific target platforms, try to use option `--target all` first, and then narrow your search scope accordingly.
--- --features serde,palettes
palette v0.1.0 (/home/learner/palette)
├── palette feature "default"
│   └── color v0.1.0 (/home/learner/color)
│       ├── color feature "default" (command-line)
│       ├── color feature "palettes" (command-line)
│       └── color feature "serde" (command-line)
└── palette feature "serde"
    └── color feature "serde" (command-line)

With serde alone, palette isn't in the graph at all (cargo tree -i palette has nothing to print): the ? stopped palette?/serde from pulling it in. With both features, palette is there and has its serde feature, enabled by color feature "serde". Without the ?, serde would have forced palette into every build that wanted serialisation.

In build scripts

Cargo passes enabled features to build.rs as environment variables: CARGO_FEATURE_HEX=1, CARGO_FEATURE_SERDE=1 (upper case, - becomes _). A build script can, for example, compile an extra C file only when a feature is on (build.rs lesson).

Test yourself

What does serde = ["dep:serde", "palette?/serde"] do when the user enables only serde?

  1. Enables serde and palette with its serde feature
  2. Enables the serde dependency; palette stays off, so nothing happens to it
  3. Fails: palette is optional
  4. Enables palette without serde

Why prefer "dep:palette" over relying on the implicit feature palette?

  1. It compiles faster
  2. It hides the dependency name from your public feature list, so you can change dependencies without breaking users
  3. Implicit features are deprecated errors
  4. It enables palette's default features

How do you build without the features in default?

  1. --features none
  2. --no-default-features
  3. --minimal
  4. default = false on the command line