11# ` Option ` & ` unwrap `
22
3- In the last example, we showed that we can induce program failure at will.
4- We told our program to ` panic ` if the princess received an inappropriate
5- gift - a snake. But what if the princess expected a gift and didn't receive
3+ In the last example, we showed that we can induce program failure at will.
4+ We told our program to ` panic ` if the royal received an inappropriate
5+ gift - a snake. But what if the royal expected a gift and didn't receive
66one? That case would be just as bad, so it needs to be handled!
77
8- We * could* test this against the null string (` "" ` ) as we do with a snake.
9- Since we're using Rust, let's instead have the compiler point out cases
8+ We * could* test this against the null string (` "" ` ) as we do with a snake.
9+ Since we're using Rust, let's instead have the compiler point out cases
1010where there's no gift.
1111
12- An ` enum ` called ` Option<T> ` in the ` std ` library is used when absence is a
12+ An ` enum ` called ` Option<T> ` in the ` std ` library is used when absence is a
1313possibility. It manifests itself as one of two "options":
1414
1515* ` Some(T) ` : An element of type ` T ` was found
1616* ` None ` : No element was found
1717
18- These cases can either be explicitly handled via ` match ` or implicitly with
18+ These cases can either be explicitly handled via ` match ` or implicitly with
1919` unwrap ` . Implicit handling will either return the inner element or ` panic ` .
2020
21- Note that it's possible to manually customize ` panic ` with [ expect] [ expect ] ,
22- but ` unwrap ` otherwise leaves us with a less meaningful output than explicit
23- handling. In the following example, explicit handling yields a more
21+ Note that it's possible to manually customize ` panic ` with [ expect] [ expect ] ,
22+ but ` unwrap ` otherwise leaves us with a less meaningful output than explicit
23+ handling. In the following example, explicit handling yields a more
2424controlled result while retaining the option to ` panic ` if desired.
2525
2626``` rust,editable,ignore,mdbook-runnable
@@ -35,9 +35,9 @@ fn give_commoner(gift: Option<&str>) {
3535 }
3636}
3737
38- // Our sheltered princess will `panic` at the sight of snakes.
38+ // Our sheltered royal will `panic` at the sight of snakes.
3939// All gifts are handled implicitly using `unwrap`.
40- fn give_princess (gift: Option<&str>) {
40+ fn give_royal (gift: Option<&str>) {
4141 // `unwrap` returns a `panic` when it receives a `None`.
4242 let inside = gift.unwrap();
4343 if inside == "snake" { panic!("AAAaaaaa!!!!"); }
@@ -57,8 +57,8 @@ fn main() {
5757 let bird = Some("robin");
5858 let nothing = None;
5959
60- give_princess (bird);
61- give_princess (nothing);
60+ give_royal (bird);
61+ give_royal (nothing);
6262}
6363```
6464
0 commit comments