Enums define a type by enumerating its possible values. Combined with pattern matching, they're incredibly powerful!
enum Direction {
North,
South,
East,
West,
}
enum Message {
Quit, // no data
Move { x: i32, y: i32 }, // named fields
Write(String), // single value
Color(u8, u8, u8), // multiple values
}Rust has no null! Instead, it uses Option<T>:
enum Option<T> {
Some(T),
None,
}Unlike null in other languages, you MUST handle both cases with Option. The compiler enforces this!
fn handle_option(opt: Option<i32>) {
match opt {
Some(value) => println!("Got: {}", value),
None => println!("Nothing"),
}
}Implement safe_divide(a, b) that:
None if b is 0Some(a / b) otherwiseOption<i32>safe_divide(10, 2) → Some(5)safe_divide(10, 0) → Nonefn safe_divide(a: i32, b: i32) -> Option<i32> {
if b == 0 {
None
} else {
Some(a / b)
}
}