1
1
# ` Option ` & ` unwrap `
2
2
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
6
6
one? That case would be just as bad, so it needs to be handled!
7
7
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
10
10
where there's no gift.
11
11
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
13
13
possibility. It manifests itself as one of two "options":
14
14
15
15
* ` Some(T) ` : An element of type ` T ` was found
16
16
* ` None ` : No element was found
17
17
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
19
19
` unwrap ` . Implicit handling will either return the inner element or ` panic ` .
20
20
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
24
24
controlled result while retaining the option to ` panic ` if desired.
25
25
26
26
``` rust,editable,ignore,mdbook-runnable
@@ -35,9 +35,9 @@ fn give_commoner(gift: Option<&str>) {
35
35
}
36
36
}
37
37
38
- // Our sheltered princess will `panic` at the sight of snakes.
38
+ // Our sheltered royal will `panic` at the sight of snakes.
39
39
// All gifts are handled implicitly using `unwrap`.
40
- fn give_princess (gift: Option<&str>) {
40
+ fn give_royal (gift: Option<&str>) {
41
41
// `unwrap` returns a `panic` when it receives a `None`.
42
42
let inside = gift.unwrap();
43
43
if inside == "snake" { panic!("AAAaaaaa!!!!"); }
@@ -57,8 +57,8 @@ fn main() {
57
57
let bird = Some("robin");
58
58
let nothing = None;
59
59
60
- give_princess (bird);
61
- give_princess (nothing);
60
+ give_royal (bird);
61
+ give_royal (nothing);
62
62
}
63
63
```
64
64
0 commit comments