Updated 'src/functional_features/closures.md'.

This commit is contained in:
Hector PENG
2026-03-29 17:55:48 +08:00
parent 0bde477ff6
commit 5318acc55d
4 changed files with 80 additions and 30 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "shirt-company"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@@ -0,0 +1,52 @@
#[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
);
}