1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
}
|