> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust Cfg Attribute

The `cfg` (configuration) attribute is a built-in Rust attribute used for conditional compilation. It instructs the Rust compiler (`rustc`) to include or exclude the annotated Abstract Syntax Tree (AST) node based on compile-time configuration predicates. If the predicate evaluates to false, the compiler completely strips the item from the AST. This evaluation and stripping occur *during* the macro expansion phase, meaning macros can generate code containing `cfg` attributes, which the compiler will then evaluate in that same pass.

## Syntax and Placement

The attribute can be applied as an outer attribute to specific items (functions, structs, modules, statements, etc.) or as an inner attribute to apply to the entire enclosing module or crate.

```rust theme={"dark"}
// Outer attribute: applies only to the item immediately following it
#[cfg(predicate)]
struct ConditionalStruct;

// Inner attribute: applies to the entire enclosing scope (e.g., top of a file)
#![cfg(predicate)]
```

## Configuration Predicates

The `cfg` attribute evaluates predicates that fall into three primary categories:

1. **Cargo Features:** The most idiomatic way developers interact with `cfg` is through Cargo features. Cargo automatically translates features defined in `Cargo.toml` into name-value pair flags (`--cfg feature="name"`) passed to `rustc`.
   ```rust theme={"dark"}
   ```

\#\[cfg(feature = "experimental\_api")]

````
2. **Name-Value Pairs:** Evaluates to true if the specific configuration key matches the provided string value. These are typically populated by the compiler based on the target triple.
   ```rust
#[cfg(target_os = "linux")]
#[cfg(target_arch = "x86_64")]
#[cfg(target_env = "msvc")]
````

3. **Boolean Flags:** Evaluates to true if the configuration flag is currently set in the compilation environment.
   ```rust theme={"dark"}
   ```

\#\[cfg(test)]
\#\[cfg(debug\_assertions)]

````

## Logical Operators
Predicates can be combined or inverted using built-in logical operators. These operators can be nested arbitrarily deep.
* **`all(...)`**: Evaluates to true if *every* comma-separated predicate within the parentheses evaluates to true.
  ```rust
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
fn windows_x64_only() {}
````

* **`any(...)`**: Evaluates to true if *at least one* comma-separated predicate within the parentheses evaluates to true.
  ```rust theme={"dark"}
  ```

\#\[cfg(any(target\_os = "macos", target\_os = "ios"))]
fn apple\_platforms\_only() {}

````
* **`not(...)`**: Evaluates to true if the single predicate within the parentheses evaluates to false.
  ```rust
#[cfg(not(test))]
fn exclude_from_tests() {}
````

## The `cfg_attr` Attribute

The `cfg_attr` attribute is a closely related built-in attribute used to conditionally apply *other* attributes to an item. It takes a configuration predicate followed by a comma-separated list of attributes to apply if the predicate evaluates to true.

```rust theme={"dark"}
// If the "serialization" feature is enabled, this expands to:
// #[derive(Serialize, Deserialize)]
// struct MyData;
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
struct MyData;
```

## Custom Configurations

Beyond Cargo features and built-in compiler targets, custom configuration flags can be passed directly to `rustc` using the `--cfg` command-line flag or emitted via a `build.rs` script using the `cargo::rustc-cfg` instruction.

```bash theme={"dark"}

# Passing a custom flag via rustc
rustc --cfg custom_flag main.rs
```

```rust theme={"dark"}
// Evaluates to true based on the compiler flag above
#[cfg(custom_flag)]
fn custom_implementation() {}
```

## The `cfg!` Macro

While the `#[cfg]` attribute removes code from the AST, Rust also provides the `cfg!()` macro for inline boolean evaluation. The macro takes the exact same predicates as the attribute but evaluates to a boolean literal (`true` or `false`) at compile time.

```rust theme={"dark"}
fn check_os() {
    let is_windows = cfg!(target_os = "windows");
    
    if is_windows {
        // This block is still parsed and type-checked on non-Windows platforms,
        // but the compiler will optimize the branch away.
    }
}
```

Unlike the `#[cfg]` attribute, code inside a branch controlled by `cfg!()` must still be syntactically valid and pass the borrow checker and type checker on all platforms, because the AST nodes are not stripped.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Rust Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
