CodeBlanks Logo Icon CodeBlanks

Features

Do conditional compilation with Cargo features.

Features

Features let you turn optional parts of a crate on and off. Unused code isn't compiled, so compile time and binary size shrink:

# Cargo.toml
[features]
default = ["metin"]
metin = []
json = ["dep:serde_json"]

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

The user chooses: fatura = { version = "1", features = ["json"] } or on the command line cargo build --features json.

Conditional compilation

Code looks at features with the #[cfg(..)] attribute or the cfg!(..) macro:

#[cfg(feature = "json")]
pub fn json_yaz(..) { .. }       // compiled only if json is on

fn bicim() -> &'static str {
    if cfg!(feature = "json") { "json" } else { "metin" }
}

#[cfg] removes the item entirely; cfg! is an expression that is true/false at compile time, and both branches must compile. The same mechanism is used for the operating system: #[cfg(target_os = "windows")].

Practice Format choice

Write fn bicim() -> &'static str returning "json" or "metin" using cfg!(feature = "json"), and print the result as biçim: .... No features are enabled in the exercise environment.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn bicim() -> &'static str {
    if cfg!(feature = "json") {
        "json"
    } else {
        "metin"
    }
}

fn main() {
    println!("biçim: {}", bicim());
}

Expected output

biçim: metin

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why should features be only <strong>additive</strong>?

  • It isn't needed
  • If two crates in the tree ask for different features, Cargo unions them; one feature must not break another Correct answer
  • It's a compiler rule
  • For performance

Explanation: Removing something from the API or inverting behaviour when a feature is on can break another user's build.

2 Conditional item

Question
#[____(feature = "json")]
pub fn json_yaz() {}
Answer
#[cfg(feature = "json")]
pub fn json_yaz() {}

Explanation: #[cfg(..)] removes the item from the build if the condition fails.

3 Syntax and meaning

Term Meaning
default = ["metin"] On by default
optional = true Optional dependency
#[cfg(feature = "x")] Conditional item
cfg!(feature = "x") Compile-time bool

All lessons in Intermediate