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.
#[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());}