Day 23: Derive Macros
MediumderiveDebugClone+1

Day 23: Derive Macros

Derive macros automatically implement traits for your types - a huge productivity boost!

Common Derivable Traits

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct User {
    name: String,
    age: u32,
}
TraitPurpose
DebugEnables {:?} formatting
CloneEnables .clone() method
CopyImplicit copying (for simple types)
PartialEqEnables == comparison
EqMarker for full equality
HashEnables use as HashMap key
DefaultEnables Type::default()
PartialOrdEnables <, > comparison
OrdFull ordering

Solana Relevance: In Anchor, you'll frequently use:

#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TokenAccount { ... }

Debug Trait

#[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

Clone vs Copy

#[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.

The Task

Add the necessary derive macros to make the code compile:

  • Debug for {:?} printing
  • Clone for .clone()
  • PartialEq for == comparison

Requirements

  • Print the token with {:?}
  • Compare two tokens with ==
  • Clone works correctly

Hints

#[derive(Debug, Clone, PartialEq)]
struct Token {
    symbol: String,
    amount: u64,
}
Language: Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Output
Run to see the result here.
    Day 23: Derive Macros · RUST Challenge | learn.sol