I am pretty new to Rust, an I'm currently having an issue with the borrow checker. This code doesn't compile:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = String::new();
let mut xs = self.xs.iter();
for x in 0..11 {
out += match x {
3 | 7 => "|",
_ => &xs.next().unwrap().to_string(),
};
}
write!(f, "{}", out)
}
I get the error
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:32:23
|
30 | out += match x {
| ____________________-
31 | | 3 | 7 => "|",
32 | | _ => &xs.next().unwrap().to_string(),
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| | | |
| | | temporary value is freed at the end of this statement
| | creates a temporary which is freed while still in use
33 | | };
| |_____________- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
However, this very similar code does compile: (of course, not with the functionality I'm looking for)
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut out = String::new();
let mut xs = self.xs.iter();
for x in 0..11 {
out += &xs.next().unwrap().to_string();
}
write!(f, "{}", out)
}
My question is, why does the first example not work if the second one does? My understanding is that the match should just be evaluated as what it's returning, so in the case where x is not 3 or 7, it should be functionally the same as the second example.
Thank you!