skip to content

In a Rust library with an optional `serde` feature, how do `#[cfg(feature = "serde")]` and `#[cfg_attr(feature = "serde", derive(...))]` differ, and what catches a misspelled feature name?

level: seniorimportance: should knowfreq 40%

answer

  1. feature is just a cfg key
  2. remove the item or the attribute
  3. helper attributes need gating too
  4. check-cfg since Cargo 1.80

basics

~20 s

#[cfg(feature = "serde")] removes the whole item when the feature is off; #[cfg_attr(feature = "serde", derive(Serialize))] keeps the item and adds the derive only when it is on. A misspelled feature name triggers the unexpected_cfgs warning, which Cargo enables since 1.80.

solid answer

~40 s

Cargo turns each enabled feature into `--cfg feature="name"`, so `feature` is an ordinary key-value cfg option. `#[cfg(feature = "serde")]` removes whatever it is attached to: right for a manual `impl Serialize` block or a `metrics` module, wrong on the struct itself, because the struct would vanish. `#[cfg_attr(feature = "serde", derive(serde::Serialize))]` expands to the listed attributes only when the predicate is true, so the type always exists and gains the derive when the feature is on. Every helper attribute such as `#[serde(rename = "type")]` needs the same `cfg_attr` wrapper, or the default build fails with "cannot find attribute `serde` in this scope". A typo like `feature = "metric"` used to be silently false; since Cargo 1.80 Cargo passes `--check-cfg` listing the declared features, and the `unexpected_cfgs` lint warns and suggests the closest name.

code

toml · 11 lines
toml
[package]
name = "fw"
version = "0.1.0"
edition = "2024"

[dependencies]
serde = { version = "1", features = ["derive"], optional = true }

[features]
metrics = []
serde = ["dep:serde"]

go deeper

for a junior

Recall that cfg removes code and cfg_attr adds attributes, and that features reach the code as feature = "name".

for a middle

Explain why the derive goes in cfg_attr, why helper attributes need the same wrapper, and what a false cfg on the struct would break.

for a senior

Diagnose a feature gate that never activates by reading the unexpected_cfgs warning, and make that lint fail CI so typos cannot ship.

for a principal

Set the crate's convention for optional integrations: one gated module, cfg_attr for derives, a CI build per feature combination, and unexpected_cfgs denied.

## Features are ordinary cfg options When Cargo builds a crate it passes each enabled feature to rustc as a **configuration option** with the key `feature`: enabling `serde` means rustc sees `--cfg feature="serde"`. To the compiler, `feature` is not special. The Reference notes that keys need not be unique, so `feature = "std"` and `feature = "serde"` can both be set, and that the `feature` key is a convention Cargo uses for compile-time options and optional dependencies. Declaring features, optional dependencies and how features unify across a dependency graph is Cargo's business; what happens in the source is this leaf's. Inside the code you therefore test features with the same two attributes as anything else. The difference between them decides whether your type survives. ## `#[cfg]` removes, `#[cfg_attr]` adds - **`#[cfg(feature = "serde")]`** removes the whole form it is attached to when the predicate is false. On a manual `impl serde::Serialize for Event` block or on a `metrics` module that is exactly right. On the struct itself it is wrong: with the feature off, `Event` disappears and every use of it fails to resolve. - **`#[cfg_attr(feature = "serde", derive(serde::Serialize))]`** keeps the item and expands to the listed attributes only when the predicate is true. When it is false, it expands to nothing. Several attributes can be listed, and the Reference notes that `cfg_attr` can nest: `cfg_attr(a, cfg_attr(b, attr))` behaves like `cfg_attr(all(a, b), attr)`. You cannot write `#[cfg(feature = "serde")]` on the line above `#[derive(Serialize)]` to gate only the derive, because an attribute applies to the item, not to the next attribute. `cfg_attr` exists to make one attribute conditional. ## Helper attributes need the same gate Derive macros often come with **helper attributes**, such as serde's `#[serde(rename = "type")]` on a field. A helper attribute is only known while its derive is applied. If the derive is behind `cfg_attr` but the helper is not, the default build — feature off — fails with: ```plaintext error: cannot find attribute `serde` in this scope ``` So every helper is wrapped too: `#[cfg_attr(feature = "serde", serde(rename = "type"))]`. A good review habit is to grep the crate for each derive's helper name and check that every occurrence has a matching `cfg_attr`. ## When a feature name is misspelled A cfg predicate that names something nobody sets is simply false. Historically, `#[cfg(feature = "metric")]` in a crate whose feature is called `metrics` compiled cleanly in every configuration, and the gated code was silently never built. **Checked cfg** fixes this: 1. rustc's `--check-cfg` flag (stable since 1.79) declares the expected cfg names and values. When at least one is passed, rustc also expects its **well-known names** such as `target_os`, `unix` and `debug_assertions`. 2. Since **Cargo 1.80**, Cargo always passes `--check-cfg`, listing every feature declared in `[features]` as an expected value of `feature`. 3. Any cfg whose name or value is not expected triggers the **`unexpected_cfgs`** lint. Its default level is **warn**, and its message names the closest expected value, for example "there is a expected value with a similar name: `\"metrics\"`". The same lint catches `target_os = "macosx"` and suggests `"macos"`. Custom names that are not features, such as a `--cfg my_backend` passed through flags or a build script, must be declared too, through `check-cfg` in the `[lints.rust]` table or `cargo::rustc-check-cfg` from the build script; those mechanisms belong with Cargo. Plain rustc without any `--check-cfg` flag does not check at all. ## Choosing the right form | Need | Use | |---|---| | Add a derive only with the feature | `#[cfg_attr(feature = "x", derive(...))]` | | Add a helper attribute for that derive | `#[cfg_attr(feature = "x", ...)]` on the field | | Add a whole module, function or impl block | `#[cfg(feature = "x")]` on that item | | Skip a statement in a function body | `#[cfg(feature = "x")]` on the statement | | Read the flag as a value | `cfg!(feature = "x")`, when both branches compile without the feature | ## Making it hold in practice - Treat `unexpected_cfgs` as an error in CI, with `-D warnings` or by raising the lint's level, because a warning still produces a build with the gated code missing. - Build the default features, `--no-default-features` and each optional feature on its own, since a gate that is wrong only in one combination is invisible in the others. - Keep each integration behind one gated module where possible, so the number of `cfg(feature = ...)` lines stays small enough to review. The senior answer names both attributes, explains why the derive uses `cfg_attr` and why its helpers must follow it, and knows that since Cargo 1.80 a misspelled feature is a visible `unexpected_cfgs` warning rather than code that silently never compiles.

  • Why not put `#[cfg(feature = "serde")]` directly above `#[derive(serde::Serialize)]`?
    An attribute cannot apply to another attribute: `#[cfg]` applies to the whole item, so the struct itself disappears when the feature is off and every use of it fails with a name-resolution error. `cfg_attr` exists precisely to make one attribute conditional while the item stays.
  • Does `unexpected_cfgs` also cover custom names such as `#[cfg(my_backend)]` passed with `--cfg`?
    Yes. Any name or value outside the expected list is reported, so a custom cfg must be declared: statically with `check-cfg` under `[lints.rust] unexpected_cfgs` in Cargo.toml, or with `cargo::rustc-check-cfg` from a build script; both are covered with Cargo. Plain rustc lints only when at least one `--check-cfg` flag is passed.
  • Is `unexpected_cfgs` an error by default?
    No, its default level is warn, so a typo still builds and the gated code is silently left out. Teams usually promote it with `-D warnings` in CI, or by setting the lint's level to deny, so a misspelled feature cannot reach a release.

  • #[cfg(feature = "serde")] on a struct only removes its serde support, not the struct.
  • cfg_attr removes the item when the predicate is false.
  • Helper attributes such as serde(rename) are ignored when the derive is gated off.
  • A misspelled feature in cfg is a hard compile error.
  • feature is a special keyword in rustc rather than an ordinary key-value cfg option.

Assumes Rust and Cargo 1.99; rustc's --check-cfg is stable since 1.79 and Cargo has passed it automatically since 1.80.