liveBook · Manning

Feature flag

As explained in Code Like a Pro in Rust

A feature flag is a Cargo configuration option that enables or disables optional functionality, dependencies, or code.

A feature flag is a Cargo configuration switch for optional dependencies, functionality, implementations, or compiler behavior. Disabling unused features can reduce compile times and binary size, but increases configuration complexity. section 2.3

Use feature flags to:

  • Declare optional dependencies and expose their functionality only when selected. section 2.3
  • Forward configuration to dependencies, such as enabling SIMD, assembly, or architecture-specific backends. section 2.3
  • Keep nightly-only functionality opt-in while preserving stable-toolchain support for users who need it. section 3.7 section 3.7.1

Manifest and source gating

A manifest can define optional dependencies and a default backend:\n\n[dependencies]\nserde = { version = "1.0", optional = true, features = ["derive"] }\n\n[features]\ndefault = ["u64_backend"]\nsimd_backend = ["curve25519-dalek/simd_backend", "sha2/asm"]\n\nSource can then conditionally import and derive support:\n\n#[cfg(feature = "serde")]\nuse serde::{Deserialize, Serialize};\n\n#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]\nstruct Message { /* ... */ }\n\nFeature definitions are Boolean, and mutually exclusive backends require deliberate configuration and validation. section 2.3

Listing 3.3 Code for lib.rs from dryoc
#![cfg_attr(
    any(feature = "nightly", all(feature = "nightly", doc)),    #1
    feature(allocator_api, doc_cfg)                             #2
)]

Inspect how a nightly feature flag conditionally enables allocator_api and doc_cfg. section 3.7.1

How Code Like a Pro in Rust covers it

How deep it goes
Explains Boolean feature definitions, dependency propagation, cfg integration, and trade-offs, but stops short of exhaustive Cargo semantics.
Examples
Uses serde, base64, SIMD, architecture backends, Cargo manifests, cfg-gated imports, and nightly compiler attributes.
What it assumes
Assumes Rust and Cargo familiarity while introducing optional dependencies, feature declarations, and cfg predicates.
What you can do after
Operate/configure Cargo features and conditional Rust code while evaluating compile-time, binary-size, compatibility, and maintenance trade-offs.
How it connects
Connects Cargo, optional dependencies, conditional compilation, cfg attributes, subcrates, stable Rust, and nightly Rust.

Also explained in

Compare how 8 books explain feature flag →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.