mirror of
https://github.com/rust-lang/rustlings.git
synced 2024-12-27 15:56:28 +00:00
feat(options2): better tests for layered_option
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.
This commit is contained in:
parent
fc81bb15fe
commit
836134202e
1 changed files with 11 additions and 6 deletions
|
@ -18,17 +18,22 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn layered_option() {
|
fn layered_option() {
|
||||||
let mut range = 10;
|
let range = 10;
|
||||||
let mut optional_integers: Vec<Option<i8>> = Vec::new();
|
let mut optional_integers: Vec<Option<i8>> = vec![None];
|
||||||
for i in 0..(range + 1) {
|
|
||||||
|
for i in 1..(range + 1) {
|
||||||
optional_integers.push(Some(i));
|
optional_integers.push(Some(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut cursor = range;
|
||||||
|
|
||||||
// TODO: make this a while let statement - remember that vector.pop also adds another layer of Option<T>
|
// TODO: make this a while let statement - remember that vector.pop also adds another layer of Option<T>
|
||||||
// You can stack `Option<T>`'s into while let and if let
|
// You can stack `Option<T>`s into while let and if let
|
||||||
integer = optional_integers.pop() {
|
integer = optional_integers.pop() {
|
||||||
assert_eq!(integer, range);
|
assert_eq!(integer, cursor);
|
||||||
range -= 1;
|
cursor -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert_eq!(cursor, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue