Traits standards à connaître
Intermédiaire#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
struct Id(u32);
// Conversions
impl From<u32> for Id {
fn from(n: u32) -> Self { Id(n) }
}
let id: Id = 42.into();
// Affichage utilisateur
use std::fmt;
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
Cas pratique : modéliser un état de commande pour rendre les états invalides impossibles.
enum Commande { Brouillon, Payee { montant: f64 }, Expediee { montant: f64, suivi: String }, }