Traits and generics
Standard library traits
You have been using traits from the start without knowing it. #[derive(Debug, Clone, PartialEq)] automatically generates the implementation of those traits. The most common: Debug ({:?} output), Clone (.clone()), Copy (implicit copy, for small types), PartialEq (==), Default (default value).
#[derive(Debug, Clone, Copy, PartialEq, Default)]struct Point { time: f64, value: f64,} fn main() { let origin = Point::default(); // { time: 0.0, value: 0.0 } let p = Point { time: 1.0, value: 101.5 }; let q = p; // Copy : p reste utilisable println!("{origin:?} {}", p == q);}Display cannot be derived: it is the human-facing output, and the format is yours to choose. We already implemented it for our errors. From defines a conversion from one type to another; implementing it gives you into() for free in the other direction, and lets ? convert errors automatically.
use std::fmt; struct Money { cents: i64,} impl fmt::Display for Money { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}.{:02} EUR", self.cents / 100, self.cents % 100) }} impl From<f64> for Money { fn from(amount: f64) -> Self { Money { cents: (amount * 100.0).round() as i64 } }} fn main() { let a = Money::from(1234.5); let b: Money = 99.999.into(); // into() vient gratuitement de From println!("{a} / {b}"); // 1234.50 EUR / 100.00 EUR}Your turn
Implement Display for Rate so that 0.0315 prints as "3.15 %", and From<f64> so you can write let r: Rate = 0.0315.into();.
use std::fmt; struct Rate(f64); // implémente Display et From<f64> ici fn main() { let r: Rate = 0.0315.into(); println!("{r}"); // 3.15 %}Inside fmt, use write!(f, ...) exactly like println!. From has a single function: fn from(value: f64) -> Self.
use std::fmt; struct Rate(f64); impl fmt::Display for Rate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:.2} %", self.0 * 100.0) }} impl From<f64> for Rate { fn from(value: f64) -> Self { Rate(value) }} fn main() { let r: Rate = 0.0315.into(); println!("{r}"); // 3.15 %}You implement From, never Into directly: the standard library provides Into automatically for every type that has a From.