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.
  1. // An integer division that doesn't `panic!`
  2. fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
  3. if divisor == 0 {
  4. // Failure is represented as the `None` variant
  5. None
  6. } else {
  7. // Result is wrapped in a `Some` variant
  8. Some(dividend / divisor)
  9. }
  10. }
  11. // This function handles a division that may not succeed
  12. fn try_division(dividend: i32, divisor: i32) {
  13. // `Option` values can be pattern matched, just like other enums
  14. match checked_division(dividend, divisor) {
  15. None => println!("{} / {} failed!", dividend, divisor),
  16. Some(quotient) => {
  17. println!("{} / {} = {}", dividend, divisor, quotient)
  18. },
  19. }
  20. }
  21. fn main() {
  22. try_division(4, 2);
  23. try_division(1, 0);
  24. // Binding `None` to a variable needs to be type annotated
  25. let none: Option<i32> = None;
  26. let _equivalent_none = None::<i32>;
  27. let optional_float = Some(0f32);
  28. // Unwrapping a `Some` variant will extract the value wrapped.
  29. println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());
  30. // Unwrapping a `None` variant will `panic!`
  31. println!("{:?} unwraps to {:?}", none, none.unwrap());
  32. }