在我修改的以下法典中,第13章
#[derive(Debug)]
enum ShirtColor {
Red,
Blue,
Yello,
}
struct Inventory {
shirts: Vec<ShirtColor>,
}
impl< a> Inventory {
fn giveaway(&self, user_pref: Option<& a ShirtColor>) -> & a ShirtColor {
user_pref.unwrap_or_else(|| self.most_stocked())
}
fn most_stocked(&self) -> & a ShirtColor {
let mut red_count = 0;
let mut blue_count = 0;
let mut yello_count = 0;
for color in &self.shirts {
match color {
ShirtColor::Red => red_count += 1,
ShirtColor::Blue => blue_count += 1,
ShirtColor::Yello => yello_count += 1,
}
}
if red_count > blue_count && red_count > yello_count {
&ShirtColor::Red
} else if blue_count > red_count && blue_count > yello_count {
&ShirtColor::Blue
} else {
&ShirtColor::Yello
}
}
}
fn main() {
let store = Inventory {
shirts: vec![
ShirtColor::Blue,
ShirtColor::Red,
ShirtColor::Blue,
ShirtColor::Yello,
ShirtColor::Yello,
ShirtColor::Yello,
],
};
let user_pref1 = Some(&ShirtColor::Red);
let giveaway1 = store.giveaway(user_pref1);
println!(
"The user with preference {:?} gets {:?}",
user_pref1, giveaway1
);
let user_pref2 = None;
let giveaway2 = store.giveaway(user_pref2);
println!(
"The user with preference {:?} gets {:?}",
user_pref2, giveaway2
);
}
我很想知道,为什么我可以回过来提及<代码>ShirtColor备选案文。 方法
What I think is that these values will died when we go out of the method so there will be a dangling reference here
I know I am wrong so can any one explain why this code is valid ?