]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch13-functional-features/listing-13-01/src/main.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / src / doc / book / listings / ch13-functional-features / listing-13-01 / src / main.rs
1 #[derive(Debug, PartialEq, Copy, Clone)]
2 enum ShirtColor {
3 Red,
4 Blue,
5 }
6
7 struct Inventory {
8 shirts: Vec<ShirtColor>,
9 }
10
11 impl Inventory {
12 fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
13 user_preference.unwrap_or_else(|| self.most_stocked())
14 }
15
16 fn most_stocked(&self) -> ShirtColor {
17 let mut num_red = 0;
18 let mut num_blue = 0;
19
20 for color in &self.shirts {
21 match color {
22 ShirtColor::Red => num_red += 1,
23 ShirtColor::Blue => num_blue += 1,
24 }
25 }
26 if num_red > num_blue {
27 ShirtColor::Red
28 } else {
29 ShirtColor::Blue
30 }
31 }
32 }
33
34 fn main() {
35 let store = Inventory {
36 shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
37 };
38
39 let user_pref1 = Some(ShirtColor::Red);
40 let giveaway1 = store.giveaway(user_pref1);
41 println!(
42 "The user with preference {:?} gets {:?}",
43 user_pref1, giveaway1
44 );
45
46 let user_pref2 = None;
47 let giveaway2 = store.giveaway(user_pref2);
48 println!(
49 "The user with preference {:?} gets {:?}",
50 user_pref2, giveaway2
51 );
52 }