rust / beginner
Snippet
Using Derive Macros for Common Traits
The derive attribute automatically implements traits for structs. Debug allows printing with {:?}, Clone enables duplication, and PartialEq allows equality comparisons with ==.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[derive(Debug, Clone, PartialEq)]struct Point {x: f64,y: f64,}fn main() {let p1 = Point { x: 1.0, y: 2.0 };let p2 = p1.clone();println!("Point: {:?}", p1);println!("Clone: {:?}", p2);println!("Equal: {}", p1 == p2);}
Breakdown
1
#[derive(Debug, Clone, PartialEq)]
Attribute that auto-implements Debug, Clone, and PartialEq traits
2
struct Point {
Struct definition for a 2D point with floating coordinates
3
x: f64,
Field for the x-coordinate, 64-bit floating point
4
let p1 = Point { x: 1.0, y: 2.0 };
Creates first Point instance
5
let p2 = p1.clone();
Creates a deep copy of p1 using the derived Clone trait
6
println!("Point: {:?}", p1);
Uses Debug trait to print the struct in debug format