Structs
Intermédiaire#[derive(Debug, Clone, PartialEq)]
struct Utilisateur {
nom: String,
email: String,
age: u32,
}
let mut u = Utilisateur {
nom: String::from("Alice"),
email: String::from("alice@example.com"),
age: 30,
};
u.age += 1;
// Syntaxe de mise à jour : reprendre les autres champs
let v = Utilisateur { nom: String::from("Bob"), ..u.clone() };
println!("{u:?}"); // Debug
println!("{u:#?}"); // Debug lisible sur plusieurs lignes
Méthodes avec impl#
impl Utilisateur {
// Fonction associée (pas de self) : équivalent d'un constructeur
fn new(nom: &str, email: &str) -> Self {
Self { nom: nom.to_string(), email: email.to_string(), age: 0 }
}
// &self : lecture ; &mut self : modification ; self : consomme l'objet
fn est_majeur(&self) -> bool { self.age >= 18 }
fn vieillir(&mut self) { self.age += 1; }
}
let mut u = Utilisateur::new("Alice", "alice@example.com");
u.vieillir();