836134202e
The existing test can be solved with the following: ```rs while let Some(integer) = optional_integers.pop() { assert_eq!(integer.unwrap(), range); ``` Similarly with `expect(...)`, `unwrap_or(0)`, `unwrap_or_default()`, etc. However, none of these solutions use the learning point of stacking `Option<T>`s. The updated test can _only_ be solved by stacking `Option<T>`s: ```rs while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, cursor); ``` With the updated test, using `unwrap` or `expect` will panic when it hits the `None` value, and using `unwrap_or` or `unwrap_or_default` will cause the final `assert_eq!(cursor, 0)` to panic. |
||
---|---|---|
.. | ||
options1.rs | ||
options2.rs | ||
options3.rs | ||
README.md |
Options
Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code, as they have a number of uses:
- Initial values
- Return values for functions that are not defined over their entire input range (partial functions)
- Return value for otherwise reporting simple errors, where None is returned on error
- Optional struct fields
- Struct fields that can be loaned or "taken"
- Optional function arguments
- Nullable pointers
- Swapping things out of difficult situations