Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 132 ยท Modules, Packages and Macros

Attributes, cfg and Conditional Compilation

Learn Rust attributes: derive, cfg and cfg!, #[cfg(test)], inline, must_use, repr, allow, deprecated, cfg_attr, feature flags and target_os checks with examples.

An attribute is a piece of metadata attached to code. It starts with #[ and ends with ], and it tells the compiler (or a tool, or a macro) something about the item below it. You have used #[derive(Debug)] and #[test] already. This lesson is a tour of the attributes you will meet most often and, in particular, of conditional compilation: including or excluding code depending on the platform, the build mode, or a feature flag.

Attributes come in two spellings. #[name] applies to the item that follows it. #![name] (with an exclamation mark) applies to the thing that contains it, typically the whole crate or module, and must appear at the top. Both can carry arguments: #[allow(dead_code)], #[repr(u8)], #[cfg(target_os = "linux")].

Where attributes go

Attributes can be placed on items (functions, structs, enums, modules, impls, use), on struct fields and enum variants, on function parameters, on statements and on expressions (a few of them). Several can be stacked:

Rust Stacking attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Without #[allow(dead_code)] the compiler would warn that the variants North, South and West are never constructed. The attribute on the field name silences the warning for that one field only. Always make suppressions as narrow as possible so they do not hide real problems elsewhere.

Lint attributes: allow, warn, deny, forbid, expect

Lints are the compiler's and Clippy's checks. Four attributes set the level for a lint:

Attribute Effect
#[allow(lint)] do not report
#[warn(lint)] report as a warning
#[deny(lint)] report as an error
#[forbid(lint)] like deny, but nested code cannot loosen it
#[expect(lint)] like allow, but warns if the lint turns out to be unnecessary

#[expect] (stable since Rust 1.81) is the best choice for deliberate suppressions, because it tells you when you can delete it:

Rust allow versus expect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler prints a warning for third: the expectation was not fulfilled, so the suppression is stale. first stays silent forever, even after you fix the code. At crate level, #![deny(missing_docs)] or #![forbid(unsafe_code)] are popular ways to set project policy.

#[must_use]: do not ignore this

Mark a function or type with #[must_use] and the compiler warns when its result is thrown away. Result and Option-returning iterators already behave this way, which is why ignoring an error gives a warning. You can add a message:

Rust must_use produces a warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get two warnings: unused return value of add_tax that must be used with your message, and unused Ticket that must be used. The fix is to use the value or to write let _ = add_tax(100.0); to say "I know and I do not care". Use #[must_use] on builder methods that return a new value instead of mutating, and on guard types.

#[deprecated]

Mark old APIs with #[deprecated] to nudge callers toward the replacement without breaking them:

Rust deprecated gives a warning at the call site

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The warning reads use of deprecated function area: use area_of instead. The program still runs. The since and note fields are optional but make the warning actionable.

#[inline] and friends

#[inline] is a hint that the function body should be copied into callers. The compiler already inlines small functions inside one crate by itself, so you mostly need it for small public functions in a library, where callers in other crates cannot otherwise see the body. #[inline(always)] and #[inline(never)] are stronger requests. Do not sprinkle them everywhere: measure first.

Other performance-flavoured attributes: #[cold] marks a rarely called path, and #[track_caller] makes a panic report the caller's line instead of the function's own. That one is useful in your own helpers:

Rust track_caller points panics at the caller (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program panics with expected a positive number, got -2 and exit code 101. The location in the message names the line in main where you called must_be_positive(-2), not the line of the panic! inside the helper. That is exactly how unwrap() and expect() report their location.

#[repr]: choosing the memory layout

By default the compiler is free to reorder the fields of a struct to save space. #[repr(...)] takes that freedom away or changes representation:

  • #[repr(C)] lays fields out in declaration order like a C struct. Needed for FFI.
  • #[repr(u8)] (or u16, i32, ...) on an enum sets the discriminant type.
  • #[repr(transparent)] guarantees a single-field wrapper has the same layout as its field.
  • #[repr(packed)] removes padding (and makes references to fields dangerous); #[repr(align(N))] raises the alignment.
Rust repr changes size and discriminants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

With default layout the compiler places the u32 first and packs the two u8 values after it: 8 bytes total. repr(C) keeps the declared order, so padding after a and c makes it 12 bytes. Layout is covered in depth in Memory Layout and Sizes.

Conditional compilation with #[cfg]

#[cfg(condition)] includes the item only if the condition is true. If it is false, the code is removed before type checking, so it may even refer to things that do not exist on this platform. Conditions are built from predicates:

Predicate Example True when
target_os target_os = "linux" compiling for that OS (windows, macos, linux, android, ...)
target_family unix, windows shorthand family
target_arch target_arch = "x86_64" CPU architecture
target_pointer_width = "64" pointer size
target_endian = "little" byte order
debug_assertions debug_assertions debug-style builds
test test compiling the test harness
feature feature = "serde" Cargo feature enabled
panic panic = "unwind" panic strategy

Combine with all(...), any(...) and not(...):

Rust Selecting code per platform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Exactly one platform function survives for any target, so there is no duplicate-definition error. On our server (Linux) the output says the Unix-like line and "64-bit build". On your own laptop it will say what matches your system. The same attribute works on use statements, modules, impl blocks, struct fields, statements and match arms.

cfg!() versus #[cfg]

cfg!(condition) is a macro that expands to true or false. Both branches of an if cfg!(...) must still compile on every platform, because the code is not removed. Use #[cfg] when the excluded code might not compile (it names a Windows-only API, for example), and cfg! when both versions compile and you just want a runtime-looking choice that the optimizer folds away.

Rust cfg! gives a boolean, #[cfg] removes code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Our editor compiles with debug assertions on, so the debug-only block appears. In a cargo build --release build it would be gone from the binary entirely.

#[cfg(test)] and unit tests

The most common cfg in real projects is #[cfg(test)]. A module marked with it is compiled only when you run cargo test, so test helpers and use lines never bloat the real binary:

Rust
// Read-only: needs `cargo test` (our editor builds a normal binary)
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_numbers() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    #[should_panic(expected = "overflow")]
    fn overflow_panics() {
        let _ = i32::MAX + add(1, 0);
    }

    #[test]
    #[ignore = "slow"]
    fn slow_one() {}
}

#[test], #[should_panic] and #[ignore] are attributes too. The testing chapter later in this tutorial covers them properly. Here the key idea is that #[cfg(test)] is a normal cfg whose condition is "the compiler was asked to build tests".

Feature flags

Cargo features are named switches declared in Cargo.toml. Turning one on sets feature = "name" for cfg. Libraries use them to make heavy or optional functionality opt-in:

TOML
# Cargo.toml (read-only)
[features]
default = ["json"]
json = []
fast-math = []
Rust
// src/lib.rs (read-only: features need Cargo)
#[cfg(feature = "json")]
pub fn to_json(n: i32) -> String {
    format!("{{\"value\":{n}}}")
}

pub fn compute(x: f64) -> f64 {
    #[cfg(feature = "fast-math")]
    {
        x * 0.5
    }
    #[cfg(not(feature = "fast-math"))]
    {
        x / 2.0
    }
}

You build with cargo build --features fast-math or --no-default-features. Features should be additive: turning one on must never remove functionality, because another crate in the dependency graph may turn it on without you knowing. The Crates, Dependencies and Features lesson explains the Cargo side.

cfg_attr: conditional attributes

#[cfg_attr(condition, attribute)] applies an attribute only when the condition holds. A classic use is "derive serde traits only if the user enabled the serde feature":

Rust cfg_attr applies an attribute conditionally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In this debug-style build Probe derives Debug, so the first println works. A realistic version reads #[cfg_attr(feature = "serde", derive(serde::Serialize))].

What happens with a wrong cfg

Since excluded code disappears, a typo in a condition silently removes code. Rust helps with the unexpected_cfgs lint, which warns about cfg names and values that Cargo does not know. With plain rustc there is no list of known names, but Cargo passes one, so on your machine #[cfg(feture = "json")] produces a warning. Keep the lint on.

Another common error is calling a function that exists only on some platforms from code that compiles everywhere. Then the compiler says cannot find function on the other platforms:

Rust A function that vanishes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

On our Linux server this fails with error E0425, "cannot find function only_windows in this scope", and a note saying it "found an item that was configured out". The fix is to give each platform its own definition (as in the platform() example) or to guard the call with the same #[cfg].

Handy built-in attributes at a glance

Attribute Purpose
#[derive(...)] generate trait impls (Procedural and Derive Macros)
#[test], #[should_panic], #[ignore] testing
#[inline], #[cold], #[track_caller] code generation hints
#[must_use], #[deprecated] API contracts
#[allow], #[warn], #[deny], #[forbid], #[expect] lint levels
#[repr(...)] data layout
#[cfg(...)], #[cfg_attr(...)] conditional compilation
#[non_exhaustive] forbid exhaustive matching/construction outside the crate
#[doc = "..."], #[doc(hidden)] documentation (what /// really is)
#[macro_export], #[proc_macro_derive] macros
#[unsafe(no_mangle)] keep a symbol name (an unsafe attribute, written this way in the 2024 edition)

In the 2024 edition attributes that can cause undefined behaviour, such as no_mangle, export_name and link_section, must be written as #[unsafe(no_mangle)] so the risk is visible in the source.

Whenever an attribute name is unfamiliar, search for it in the Rust Reference's "Attributes" chapter and in rustc --explain for error codes. Misspelled attribute names are compile errors, so typos do not slip by.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between #[attr] and #![attr]?

    The exclamation mark makes an inner attribute that applies to the thing containing it, usually written at the top of main.rs or lib.rs.
  2. 2. Why is #[expect(unused_variables)] often better than #[allow(unused_variables)]?

    expect behaves like allow, but if the lint never fires the compiler reports an unfulfilled expectation, so stale suppressions get cleaned up.
  3. 3. When must you use #[cfg(...)] instead of if cfg!(...)?

    cfg! just yields a boolean; both branches must still compile. #[cfg] removes the item before type checking, so it can mention platform-specific APIs.
  4. 4. What does #[cfg(test)] mod tests { ... } do?

    The test predicate is true only for the test harness build, so helper code does not end up in the normal binary.
  5. 5. Why should Cargo features be additive?

    Cargo unifies features across the dependency graph. If a feature removed functionality, enabling it somewhere else could break your crate.

Summary

  • Attributes are metadata: #[x] applies to the next item, #![x] to the enclosing one.
  • Lint attributes (allow, warn, deny, forbid, expect) control diagnostics; prefer narrow scope and expect.
  • #[must_use] and #[deprecated] make API contracts visible through warnings; #[track_caller] improves panic locations.
  • #[repr(C)], #[repr(u8)], #[repr(transparent)] fix layout and discriminant types.
  • #[cfg(...)] removes code before type checking; cfg!(...) is a boolean whose branches must both compile; cfg_attr applies attributes conditionally.
  • Conditions use target_os, target_arch, debug_assertions, test and feature, combined with all, any, not.
  • Cargo features are additive switches that become feature = "name" in cfg. They need Cargo, so those snippets are read-only here.

Next: Rc, Arc and Shared Ownership