Option Examples
This page was last reviewed on Feb 6, 2023.
Dot Net Perls
Option. Rust uses the Option enum to indicate whether a value exists or not. It uses the terms Some and None to indicate existence.
By returning an option, we can create an abstraction that indicates clearly to callers about a value's existence. If an element exists, it is Some. Otherwise it is None.
First example. To begin we introduce the test() function which returns an Option. For values greater than 0, we return a usize. Otherwise we treat the value 0 as None.
Info Unlike the Result type, we are not reporting an error condition. The Option just deals with existence, not errors.
Detail We cannot call unwrap() on a None value. Instead, consider using the if-let construct.
fn test(argument: usize) -> Option<usize> { // Return option with 0 meaning None. if argument >= 1 { Some(argument) } else { None } } fn main() { // Use if-let to unwrap an option safely. if let Some(result) = test(5) { println!("Result: {result}"); } // Cannot unwrap on a None option. let end = test(0).unwrap(); }
Result: 5 thread main panicked at called Option::unwrap() on a None value ... note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
Vec, get. Options are used throughout the standard library in Rust. For example, the get() function on a vector returns an option.
Tip This is how we can handle out-of-range accesses to a vector—get() will return None, and we can branch on this condition.
fn main() { let test = vec![1, 2]; if let Some(element) = test.get(0) { println!("Element 0: {element}"); } if let Some(element) = test.get(1000) { // Not reached, but no panic either. } }
Element 0: 1
Unwrap. When we have an option, we can use unwrap() to get its value. This will panic if the None value is present and the option does not have a wrapped value.
Tip With unwrap_or_default() we can get the wrapped value, or the default value for the type.
Here The default value of an isize is 0, so if our Option has a None value, we will get the 0 from unwrap_or_default.
Finally The unwrap() function will panic, leading the program to stop execution, if None is encountered.
fn test(argument: isize) -> Option<isize> { if argument < 0 { None } else { Some(argument) } } fn main() { // This will return 0 if None is encountered. let result = test(-100).unwrap_or_default(); println!("{result}"); // This will panic is None is encountered. let result = test(-100).unwrap(); }
0 thread main panicked at called Option::unwrap() on a None value, ... note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
Is_some. When we have an option in a Rust program, we can test it with the is_some and is_none functions. These are often useful in if-statements.
Here We parse a number from a str, and then create an option from it. The is_some function returns true.
fn main() { // Create an option. let temp = "1".parse::<i32>().unwrap(); let temp_option = if temp == 1 { Some(temp) } else { None }; if temp_option.is_some() { println!("IS SOME"); } if temp_option.is_none() { println!("Not reached"); } }
Find. With Strings and iterators, we can call find() functions in Rust programs. These return an option—we often handle this with if-let statements.
A summary. With its values Some and None, the Option type indicates existence. It can be used to tell us whether an index is out-of-range, as with the vec get() function.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 6, 2023 (edit link).
© 2007-2024 Sam Allen.