Optional values
The main type in this module Option. It can be used to represent a value that may or may not be present. An Option type can be some or none.
fn divide(a: i32, b: i32) -> Option<i32> {
if b == 0 {
Option::none()
} else {
Option::some(a / b)
}
}
let quotient = divide(2, 1);
if quotient.is_some() {
println!("{}", quotient.unwrap()); // unwrap panics if the value is none
}
Run this example
An Option type is useful for return values that may legitimately have no value. If an operation is expected to produce a value, but can encounter an error, it is more idiomatic to represent it with Result.
Option types can be combined in a method-chaining style using combinators such as map and and_then. They can also be unpacked with using try expressions.
Structs
Optional value
Types
-
type AnyOption = SameBaseAs<Option<()>>
Protocol that matches all Option types
Example
use std::option::AnyOption; let a = Option::some(1); let b: Option<i32> = Option::none(); let c = 42; assert!(a is AnyOption); assert!(b is AnyOption); assert!(!(c is AnyOption));
Run this example
Macros
Extract the value or short-circuit the calling function.