Structs, enums and pattern matching
Enums
A Rust enum looks like a Java enum at first sight, but each variant can carry its own data, in a different shape. It is the equivalent of a Kotlin sealed class: a closed set of cases known to the compiler.
#[derive(Debug)]enum Order { Market { quantity: f64 }, Limit { quantity: f64, price: f64 }, Cancel(u64),} fn main() { let orders = vec![ Order::Market { quantity: 100.0 }, Order::Limit { quantity: 50.0, price: 151.0 }, Order::Cancel(42), ]; for order in &orders { println!("{order:?}"); }}Order type, so a single Vec<Order> is possible.The most important enum in the standard library is Option<T>. Rust has no null: a value that may be missing has type Option<T>, which is either Some(value) or None. The compiler forces you to handle the None case before using the value.
fn find_rate(tenor_years: u32) -> Option<f64> { match tenor_years { 1 => Some(0.031), 5 => Some(0.028), _ => None, }} fn main() { let rate = find_rate(5); // let doubled = rate * 2.0; // erreur : Option<f64> n'est pas un f64 if let Some(r) = rate { println!("taux 5 ans : {r}"); } println!("taux 3 ans : {:?}", find_rate(3)); // None}Your turn
Declare a Rating enum with three variants: Investment, Speculative and Default. Give it a weight(&self) -> f64 method returning 0.2, 1.0 and 1.5.
// déclare l'enum et son impl ici fn main() { println!("{}", Rating::Speculative.weight()); // 1}Enums have impl blocks too. Inside the method, a match self covers the three variants.
enum Rating { Investment, Speculative, Default,} impl Rating { fn weight(&self) -> f64 { match self { Rating::Investment => 0.2, Rating::Speculative => 1.0, Rating::Default => 1.5, } }} fn main() { println!("{}", Rating::Speculative.weight()); // 1}If you later add a fourth variant, the compiler will flag every match that does not handle it. That is the big strength of enums over an open class hierarchy.