From 836134202ef505e03e8177565e512059488aded2 Mon Sep 17 00:00:00 2001 From: lionel-rowe Date: Fri, 21 Apr 2023 06:05:25 +0100 Subject: [PATCH] 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`s. The updated test can _only_ be solved by stacking `Option`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. --- exercises/options/options2.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4e36443..337c426 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -18,17 +18,22 @@ mod tests { #[test] fn layered_option() { - let mut range = 10; - let mut optional_integers: Vec> = Vec::new(); - for i in 0..(range + 1) { + let range = 10; + let mut optional_integers: Vec> = vec![None]; + + for i in 1..(range + 1) { 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 - // You can stack `Option`'s into while let and if let + // You can stack `Option`s into while let and if let integer = optional_integers.pop() { - assert_eq!(integer, range); - range -= 1; + assert_eq!(integer, cursor); + cursor -= 1; } + + assert_eq!(cursor, 0); } }