Home
# Fonctions associées --- ## Nouvelle instance ```rust [2-5|6,13|7-9|10-12|15|] #[derive(Debug)] // Permet l'affichage avec {:?} struct Rectangle { width: u32, height: u32, } impl Rectangle { // Bloc impl fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } } fn square(side: u32) -> Rectangle { Rectangle::new(side, side) } } fn main() { let square = Rectangle::square(10); println!("Un carré est un rectangle particulier: {:?}.", square); } ``` --- ## Le mot-clé `Self` ```rust [7-9|] #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn new(width: u32, height: u32) -> Self { Rectangle { width, height } } } fn main() { let rect = Rectangle::new(10, 20); println!("Ceci est un rectangle: {:?}.", rect); } ``` --- # Méthodes --- ## Le mot-clé `self` ```rust compile_fail [6-9|10-12|16-18|] struct Rectangle { width: u32, height: u32, } impl Rectangle { // les méthodes de Rectangle se trouvent dans un bloc impl // self est l'instance sur laquelle le sélecteur . est appelé fn area(self) -> u32 { self.width * self.height } fn perimeter(self) -> u32 { 2 * (self.width + self.height) } } fn main() { let rect = Rectangle { width: 10, height: 5 }; // Problème ? println!("La surface de ce rectangle est donnée par {} et son périmètre par {}.", rect.area(), rect.perimeter()); } ``` --- ## Le mot-clé `&self` ```rust [6-9|10-12|16-18|] struct Rectangle { width: u32, height: u32, } impl Rectangle { // les méthodes de Rectangle se trouvent dans un bloc impl // &self est une référence sur l'instance sur laquelle le sélecteur . est appelé fn area(&self) -> u32 { self.width * self.height } fn perimeter(&self) -> u32 { 2 * (self.width + self.height) } } fn main() { let rect = Rectangle { width: 10, height: 5 }; println!("La surface de ce rectangle est donnée par {} et son périmètre par {}.", rect.area(), rect.perimeter()); } ``` --- ## Le mot-clé `&mut self` ```rust #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { // les méthodes de Rectangle se trouvent dans un bloc impl // &mut self est une référence mutable sur l'instance sur laquelle le sélecteur . est appelé fn set_width(&mut self, width: u32) { self.width = width; } } fn main() { let mut rect = Rectangle {width: 10, height: 5}; // rect doit être mutable rect.set_width(1_000_000); // pour que cette ligne compile println!("On a modifié width. L'instance de rectangle est {:?}.", rect); } ``` --- ## Méthode sur un `enum` ```rust enum SomethingOrNothing
{ Nothing, Something(T), } impl
SomethingOrNothing
{ pub fn is_something(&self) -> bool { match *self { // on déréférence pour faire le match SomethingOrNothing::Something(_) => true, SomethingOrNothing::Nothing => false, } } } ```