diff options
Diffstat (limited to 'src/doc/rust-by-example/src/std/option.md')
-rw-r--r-- | src/doc/rust-by-example/src/std/option.md | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/doc/rust-by-example/src/std/option.md b/src/doc/rust-by-example/src/std/option.md new file mode 100644 index 000000000..30927e87e --- /dev/null +++ b/src/doc/rust-by-example/src/std/option.md @@ -0,0 +1,50 @@ +# `Option` + +Sometimes it's desirable to catch the failure of some parts of a program +instead of calling `panic!`; this can be accomplished using the `Option` enum. + +The `Option<T>` enum has two variants: + +* `None`, to indicate failure or lack of value, and +* `Some(value)`, a tuple struct that wraps a `value` with type `T`. + +```rust,editable,ignore,mdbook-runnable +// An integer division that doesn't `panic!` +fn checked_division(dividend: i32, divisor: i32) -> Option<i32> { + if divisor == 0 { + // Failure is represented as the `None` variant + None + } else { + // Result is wrapped in a `Some` variant + Some(dividend / divisor) + } +} + +// This function handles a division that may not succeed +fn try_division(dividend: i32, divisor: i32) { + // `Option` values can be pattern matched, just like other enums + match checked_division(dividend, divisor) { + None => println!("{} / {} failed!", dividend, divisor), + Some(quotient) => { + println!("{} / {} = {}", dividend, divisor, quotient) + }, + } +} + +fn main() { + try_division(4, 2); + try_division(1, 0); + + // Binding `None` to a variable needs to be type annotated + let none: Option<i32> = None; + let _equivalent_none = None::<i32>; + + let optional_float = Some(0f32); + + // Unwrapping a `Some` variant will extract the value wrapped. + println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap()); + + // Unwrapping a `None` variant will `panic!` + println!("{:?} unwraps to {:?}", none, none.unwrap()); +} +``` |