I have ran into an issue developing an application in Rust which I can't figure out. I am new to Rust and low level languages in general, so bear with me if this a newbie question.
The code where I get this error message is quite large, but I've managed to create a small snippet which even if it doesn't make sense in what's trying to do, it does reproduce the behavior I'm interested in.
enum Item {
Type1 {
optstrfield: Option<String>,
strfield: String,
},
}
struct Owner {
pub items: std::collections::LinkedList<Item>,
}
fn main() {
let mut owner = Owner {
items: std::collections::LinkedList::new(),
};
owner.items.push_back(Item::Type1 {
optstrfield: Some("text".to_string()),
strfield: "text".to_string(),
});
let owner_ref = &mut owner;
for item in &mut owner_ref.items {
match item {
Item::Type1 { optstrfield, strfield } => {
// This if block works
if let Some(s) = optstrfield {
println!(
"{} {}",
format!("{}", s),
format!("{}", strfield),
);
} else {
println!(
"{} {}",
format!("{}", strfield),
format!("{}", strfield),
);
}
// But the following equivalent statement doesn't
// println!(
// "{} {}",
// format!("{}", if let Some(s) = optstrfield { s } else { strfield }),
// format!("{}", strfield),
// );
}
};
}
}
I make two different (but as I see them, equivalent) uses of the matched variables in the only match arm, but only the first one compiles. The second one (commented out) makes the compiler complain about "this reinitialization might get skipped" and trying to borrow moved values.
What exactly is the difference between those two options that makes one valid but not the other?