rsRustPrimer
< Back to module

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.

rust
#[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:?}");
}
}
Three variants, three data shapes. A single 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.

rust
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.

src/main.rs
// déclare l'enum et son impl ici
fn main() {
println!("{}", Rating::Speculative.weight()); // 1
}