Derive macros are used to automatically generate common trait implementations.

For example

  1. BorshSerialize, BorshDeserialize
use borsh::{BorshSerialize, BorshDeserialize}

#[derive(BorshSerialize, BorshDeserialize)]
struct User {
	num: u32,
	pub_key: PubKey
}
  1. Debug

#[derive(Debug)]
struct User {
	name: String,
	num: u32,	
}

fn main() {
	let u = User {
		name: String::from("harkirat"),
		num: 10
	};
	println!("{:?}", u);
}
  1. Copy and Clone

    Copy Trait

    The Copy trait enables implicit duplication of values. When a type implements Copy:

    #[derive(Copy, Clone)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let p1 = Point { x: 1, y: 2 };
    let p2 = p1; // p1 is copied, not moved - p1 is still usable
    println!("{}, {}", p1.x, p2.x); // This works because Point implements Copy
    

    Clone Trait

    The Clone trait enables explicit duplication through the .clone() method:

    #[derive(Clone)]
    struct Person {
        name: String,
        age: u32,
    }
    
    let p1 = Person {
        name: "Alice".to_string(),
        age: 30,
    };
    let p2 = p1.clone(); // Explicit cloning required
    // p1 is still usable after cloning