Derive macros are used to automatically generate common trait implementations.
For example
use borsh::{BorshSerialize, BorshDeserialize}
#[derive(BorshSerialize, BorshDeserialize)]
struct User {
num: u32,
pub_key: PubKey
}
#[derive(Debug)]
struct User {
name: String,
num: u32,
}
fn main() {
let u = User {
name: String::from("harkirat"),
num: 10
};
println!("{:?}", u);
}
Copy and Clone
The Copy trait enables implicit duplication of values. When a type implements Copy:
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
The Clone trait enables explicit duplication through the .clone() method:
.clone() to duplicate a value#[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