Option & unwrap

In the last example, we showed that we can induce program failure at will.
We told our program to panic if the princess received an inappropriate
gift - a snake. But what if the princess expected a gift and didn’t receive
one? That case would be just as bad, so it needs to be handled!

We could test this against the null string ("") as we do with a snake.
Since we’re using Rust, let’s instead have the compiler point out cases
where there’s no gift.

An enum called Option<T> in the std library is used when absence is a
possibility. It manifests itself as one of two “options”:

  • Some(T): An element of type T was found
  • None: No element was found

These cases can either be explicitly handled via match or implicitly with
unwrap. Implicit handling will either return the inner element or panic.

Note that it’s possible to manually customize panic with expect,
but unwrap otherwise leaves us with a less meaningful output than explicit
handling. In the following example, explicit handling yields a more
controlled result while retaining the option to panic if desired.

  1. // The commoner has seen it all, and can handle any gift well.
  2. // All gifts are handled explicitly using `match`.
  3. fn give_commoner(gift: Option<&str>) {
  4. // Specify a course of action for each case.
  5. match gift {
  6. Some("snake") => println!("Yuck! I'm throwing that snake in a fire."),
  7. Some(inner) => println!("{}? How nice.", inner),
  8. None => println!("No gift? Oh well."),
  9. }
  10. }
  11. // Our sheltered princess will `panic` at the sight of snakes.
  12. // All gifts are handled implicitly using `unwrap`.
  13. fn give_princess(gift: Option<&str>) {
  14. // `unwrap` returns a `panic` when it receives a `None`.
  15. let inside = gift.unwrap();
  16. if inside == "snake" { panic!("AAAaaaaa!!!!"); }
  17. println!("I love {}s!!!!!", inside);
  18. }
  19. fn main() {
  20. let food = Some("cabbage");
  21. let snake = Some("snake");
  22. let void = None;
  23. give_commoner(food);
  24. give_commoner(snake);
  25. give_commoner(void);
  26. let bird = Some("robin");
  27. let nothing = None;
  28. give_princess(bird);
  29. give_princess(nothing);
  30. }