capypad
0 day streak
rust / beginner
Snippet

Basic Error Handling with Option

Rust uses the Option enum to represent a value that might be missing, instead of using null. 'match' is used to safely handle both the presence (Some) and absence (None) of the value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
fn main() {
let some_value = Some(5);
let no_value: Option<i32> = None;
 
match some_value {
Some(val) => println!("Value: {val}"),
None => println!("No value found"),
}
}
Breakdown
1
let some_value = Some(5);
Wraps the integer 5 in the 'Some' variant of the Option enum.
2
match some_value {
Starts a pattern match to inspect the contents of the Option.
3
Some(val) => ...
Executes this branch if the value exists, binding it to 'val'.