Structs, enums and pattern matching
Methods and impl blocks
Methods are declared in an impl block, separate from the struct. Their first parameter says how they use the instance, following exactly the ownership rules from the previous module.
#[derive(Debug)]struct Position { ticker: String, quantity: f64, price: f64,} impl Position { // Fonction associée (pas de self) : le constructeur par convention. fn new(ticker: &str, quantity: f64, price: f64) -> Self { Self { ticker: ticker.to_string(), quantity, price } } // &self : lecture seule. fn market_value(&self) -> f64 { self.quantity * self.price } // &mut self : modifie l'instance. fn reprice(&mut self, new_price: f64) { self.price = new_price; } // self : consomme l'instance, qui n'est plus utilisable ensuite. fn close(self) -> String { format!("{} clôturée à {}", self.ticker, self.price) }} fn main() { let mut position = Position::new("AIR.PA", 100.0, 151.25); println!("{}", position.market_value()); position.reprice(155.0); println!("{}", position.close()); // position.market_value(); // erreur : position a été consommée par close}You call an associated function with Type::function (like String::from) and a method with a dot. Rust has no special constructor: new is just a convention, and Self refers to the type being implemented.
Your turn
Add a pnl(&self, entry_price: f64) -> f64 method to Position that returns the profit or loss against the entry price.
struct Position { quantity: f64, price: f64,} impl Position { // ajoute pnl ici} fn main() { let position = Position { quantity: 100.0, price: 155.0 }; println!("{}", position.pnl(151.0)); // 400}The method changes nothing: &self is enough. Fields are accessed with self.price.
struct Position { quantity: f64, price: f64,} impl Position { fn pnl(&self, entry_price: f64) -> f64 { (self.price - entry_price) * self.quantity }} fn main() { let position = Position { quantity: 100.0, price: 155.0 }; println!("{}", position.pnl(151.0)); // 400}Picking the right receiver (&self, &mut self, self) documents intent: a reader knows without reading the body that pnl does not touch the position.