mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2026-08-19 12:43:28 +08:00
58 lines
1.2 KiB
Rust
58 lines
1.2 KiB
Rust
#[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 num_red = 0;
|
|
let mut num_blue = 0;
|
|
|
|
for color in &self.shirts {
|
|
match color {
|
|
ShirtColor::Red => num_red += 1,
|
|
ShirtColor::Blue => num_blue += 1,
|
|
}
|
|
}
|
|
|
|
if num_red > num_blue {
|
|
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! (
|
|
"选项为 {:?} 的用户,得到了 {:?}",
|
|
user_pref1, giveaway1
|
|
);
|
|
|
|
let user_pref2 = None;
|
|
let giveaway2 = store.giveaway(user_pref2);
|
|
println! (
|
|
"选项为 {:?} 的用户得到了 {:?}",
|
|
user_pref2, giveaway2
|
|
);
|
|
|
|
}
|