Enums & Option Type
Enums in Rust are algebraic data types, allowing variants to hold associated data. Rust uses the Option enum to manage null safety explicitly.
1 Associated Data & Option Null Safety
Rust enums are incredibly versatile. Variants can hold different data types. Rust has **no null keyword**. Instead, null safety is handled explicitly using the built-in **`Option<T>`** enum:
- `Some(value)`: The value exists.
- `None`: No value exists (equivalent to null).
2 Enums Code
Let's run a program declaring enums with values and processing Option states:
Rust — Enums and Options
▶ Run Code
// Enum variants holding associated values
enum Message {
Quit,
Write(String),
}
fn main() {
let msg = Message::Write(String::from("Hello variant"));
match msg {
Message::Quit => println!("Quit Variant"),
Message::Write(text) => println!("Write Variant: {}", text),
}
// Option null safety check
let score: Option = Some(95);
let empty_score: Option = None;
match score {
Some(val) => println!("Score exists: {}", val),
None => println!("No score found!"),
}
}
3 Code Challenge
Challenge: Write a function that accepts an index and returns an `Option` from a list of user names. Use a match block to handle both success and error states.