Option
Optionstd::option
. It is used to represent an optional value. Option is either Some
or None
.
fn divide(numerator: f64, denominator: f64) -> Option<f64> {if denominator == 0.0 {None} else {Some(numerator / denominator)}}fn main () {// The return value of the function is an optionlet result = divide(2.0, 3.0);// Pattern match to retrieve the valuematch result {// The division was validSome(x) => println!("Result: {x}"),// The division was invalidNone => println!("Cannot divide by 0"),}}
Speaker Notes
- See std::option for more info.