diff options
author | garhve <git@garhve.com> | 2023-01-12 08:38:57 +0800 |
---|---|---|
committer | garhve <git@garhve.com> | 2023-01-12 08:38:57 +0800 |
commit | 1d329a455ba14d2dd9951d7b1284f0e7b8feabf6 (patch) | |
tree | 07d35b503b27376a3f999bdbee94fa8d3dcc5d2e /rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src | |
parent | b01a4deacb27422c8a78791affc824d00c8841ab (diff) |
closure and iterator
Diffstat (limited to 'rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src')
-rw-r--r-- | rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src/main.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src/main.rs b/rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src/main.rs new file mode 100644 index 0000000..51e1785 --- /dev/null +++ b/rust/theBook/chapter-13-functional-language-features-iterators-and-closures/shirt_inventory/src/main.rs @@ -0,0 +1,46 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +enum ShirtColor { + Red, + Blue, +} + +struct Inventory { + shirts: Vec<ShirtColor>, +} + +impl Inventory { + fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor { + user_preference.unwrap_or_else(|| self.most_stocked()) + } + + fn most_stocked(&self) -> ShirtColor { + let mut red_num = 0; + let mut blue_num = 0; + + for color in &self.shirts { + match color { + ShirtColor::Red => red_num += 1, + ShirtColor::Blue => blue_num += 1, + } + } + if red_num > blue_num { + ShirtColor::Red + } else { + ShirtColor::Blue + } + } +} + +fn main() { + let store = Inventory { + shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue], + }; + + let user_pref1 = Some(ShirtColor::Red); + let giveaway1 = store.giveaway(user_pref1); + println!("The user with preference {:?} get {:?}",user_pref1,giveaway1); + + let user_pref2 = None; + let giveaway2 = store.giveaway(user_pref2); + println!("The user with preference {user_pref2:?} get {:?}", giveaway2); +} |