[Avg. reading time: 5 minutes]
Commonly Used Rust Attributes
In Rust, attributes provide metadata about code to the compiler.
They are written using the #[] syntax and can modify compilation behavior, enable conditional code, or automatically generate implementations.
Attributes can be applied to:
- Structs
- Enums
- Functions
- Modules
- Traits
- Crates
Trait Derivation
The #[derive(…)] attribute automatically implements common traits for a struct or enum.
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
Commonly derived traits include:
- Debug
- Clone
- Copy
- PartialEq
- Eq
- Default
Example:
#[derive(Debug, Default)]
struct Config {
retries: u32,
}
Conditional Compilation
The #[cfg(…)] attribute allows code to be compiled only when specific conditions are met.
Example: compile code only during testing.
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
Example: enable code when a feature flag is enabled.
#[cfg(feature = "serde")]
use serde::Serialize;
Test Functions
The #[test] attribute marks a function as a unit test. These tests are executed when running:
cargo test
Example:
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}
Compiler Warning Control
Rust provides attributes to control compiler warnings.
#[allow(…)] suppresses specific warnings.
#[allow(dead_code)]
fn unused_function() {}
#[deny(…)] converts warnings into compilation errors.
#[deny(missing_docs)]
pub fn important_function() {}
Deprecating Code
The #[deprecated] attribute marks a function or item as deprecated.
#[deprecated(note = "use new_function instead")]
fn old_function() {}
When used, the compiler generates a warning suggesting the replacement.
Must Use Return Value
The #[must_use] attribute tells the compiler to warn if the return value of a function is ignored.
#[must_use]
fn compute() -> i32 {
42
}
compute(); // compiler will warn that result is unused
This is often used in APIs where ignoring the result may indicate a bug.