patternrustTip
derive macros: auto-implementing common traits
Viewed 0 times
derivemacroDebugClonePartialEqHashserdeboilerplate
Error Messages
Problem
Manually implementing Debug, Clone, PartialEq and similar traits for every struct is boilerplate-heavy and error-prone.
Solution
Use #[derive(...)] to auto-implement standard and library traits:
use serde::{Deserialize, Serialize};
#[derive(
Debug, // enables {:?} formatting
Clone, // enables .clone()
PartialEq, // enables == and !=
Eq, // total equality (requires PartialEq)
Hash, // enables use as HashMap key
Serialize, // serde JSON serialization
Deserialize, // serde JSON deserialization
)]
struct User {
id: u64,
username: String,
email: String,
}
let u1 = User { id: 1, username: String::from("alice"), email: String::from("a@b.com") };
let u2 = u1.clone();
println!("{:?}", u1);
assert_eq!(u1, u2);Why
Derive macros expand at compile time, generating correct boilerplate implementations based on the struct's fields. They are zero-cost — the generated code is identical to what you would write manually.
Gotchas
- All fields must implement the derived trait — deriving Hash on a struct with a float field fails because f32/f64 do not implement Hash
- PartialOrd/Ord derive compares fields in declaration order — reorder fields if you need a different comparison
- Custom derive (proc macros) from crates like serde require the crate as a dependency with its derive feature enabled
Revisions (0)
No revisions yet.