rust / intermediate
Snippet
Implementierung von Standard-Traits: Default, Clone und From
Die Implementierung von Standard-Bibliothek-Traits ermöglicht Ihren Typen, sich nahtlos in Rust's Ökosystem zu integrieren. Das Default-Trait bietet einen Fallback-Wert, wenn keine spezifischen Daten benötigt werden. Clone-Trait (ableitbar) erstellt eine tiefe Kopie Ihrer Daten. From und Into Traits ermöglichen Konvertierung zwischen Typen - wenn Sie From für einen Typ implementieren, ist Into automatisch verfugbar. Dieses Muster ist idiomatisch Rust: anstatt mehrere Konstruktoren zu haben, implementieren Sie allgemeine Traits, die gut mit der Standardbibliothek zusammenarbeiten.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#[derive(Debug, Clone)]struct Point {x: f64,y: f64,}#[derive(Debug)]struct Line {start: Point,end: Point,}impl Default for Line {fn default() -> Self {Self {start: Point { x: 0.0, y: 0.0 },end: Point { x: 1.0, y: 1.0 },}}}impl From<(f64, f64)> for Point {fn from(coords: (f64, f64)) -> Self {Point { x: coords.0, y: coords.1 }}}impl From<Point> for (f64, f64) {fn from(point: Point) -> Self {(point.x, point.y)}}impl Line {fn new(start: Point, end: Point) -> Self {Self { start, end }}fn length(&self) -> f64 {let dx = self.end.x - self.start.x;let dy = self.end.y - self.start.y;(dx * dx + dy * dy).sqrt()}}fn main() {let default_line = Line::default();println!("Default line: {:?}", default_line);let point_from_tuple: Point = (3.0, 4.0).into();println!("Point from tuple: {:?}", point_from_tuple);let tuple_from_point: (f64, f64) = point_from_tuple.into();println!("Tuple from point: {:?}", tuple_from_point);let line = Line::new((0.0, 0.0).into(), (3.0, 4.0).into());println!("Line length: {:.2}", line.length());}
Erklärung
1
#[derive(Debug, Clone)]
Leite Debug zum Drucken und Clone zum Erstellen von Kopien von Point ab
2
struct Point { x: f64, y: f64 }
Einfache 2D-Punktstruktur mit Fließkomma-Koordinaten
3
impl Default for Line {
Manuelle Default-Implementierung für Line da sie Non-Default-Felder enthalt
4
fn default() -> Self {
Gebe eine Line mit Standard-Einheitsdiagonale von (0,0) nach (1,1) zurück
5
impl From<(f64, f64)> for Point {
Implementiere Konvertierung VON Tuple ZU Point
6
impl From<Point> for (f64, f64) {
Implementiere Konvertierung VON Point ZU Tuple (umgekehrte Richtung)
7
fn main() {
Demonstriere die Traits in Aktion
8
Line::default()
Erstellt eine Line unter Verwendung der Default-Implementierung
9
Point::from((3.0, 4.0))
Konvertiere Tuple (3.0, 4.0) zu Point unter Verwendung des From-Traits
10
let tuple_from_point: (f64, f64) = point.into();
Konvertiere Point zurück zu Tuple unter Verwendung der umgekehrten From-Implementierung
11
Line::new((0.0, 0.0).into(), (3.0, 4.0).into())
Verkette .into()-Aufrufe um eine Line direkt aus Tuples zu erstellen