capypad
0 Tage Serie
rust / beginner
Snippet

Verwendung von Derive-Makros fur haufige Traits

Das derive-Attribut implementiert automatisch Traits fur Structs. Debug erlaubt das Ausgeben mit {:?}, Clone ermoglicht die Duplizierung, und PartialEq erlaubt Vergleich mit ==.

snippet.rs
rust
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);
}
Erklärung
1
#[derive(Debug, Clone, PartialEq)]
Attribut, das Debug, Clone und PartialEq Traits automatisch implementiert
2
struct Point {
Struct-Definition fur einen 2D-Punkt mit Flieskommakoordinaten
3
x: f64,
Feld fur die x-Koordinate, 64-Bit Flieskommazahl
4
let p1 = Point { x: 1.0, y: 2.0 };
Erstellt die erste Point-Instanz
5
let p2 = p1.clone();
Erstellt eine tiefe Kopie von p1 unter Verwendung des abgeleiteten Clone-Traits
6
println!("Point: {:?}", p1);
Verwendet den Debug-Trait um das Struct im Debug-Format auszugeben