Derive macros automatically implement traits for your types - a huge productivity boost!
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct User {
name: String,
age: u32,
}| Trait | Purpose |
|---|---|
Debug | Enables {:?} formatting |
Clone | Enables .clone() method |
Copy | Implicit copying (for simple types) |
PartialEq | Enables == comparison |
Eq | Marker for full equality |
Hash | Enables use as HashMap key |
Default | Enables Type::default() |
PartialOrd | Enables <, > comparison |
Ord | Full ordering |
Solana Relevance: In Anchor, you'll frequently use:
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TokenAccount { ... }#[derive(Debug)]
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
println!("{:?}", p); // Point { x: 1, y: 2 }
println!("{:#?}", p); // Pretty-printed#[derive(Clone, Copy)] // Copy requires Clone
struct Point { x: i32, y: i32 }
let p1 = Point { x: 1, y: 2 };
let p2 = p1; // Copy happens automatically
// p1 is still valid!Copy can only be derived for types whose fields are all Copy. Types with heap data (like String) cannot be Copy.
Add the necessary derive macros to make the code compile:
Debug for {:?} printingClone for .clone()PartialEq for == comparison{:?}==#[derive(Debug, Clone, PartialEq)]
struct Token {
symbol: String,
amount: u64,
}