Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let a = String::from("long string");
let result = {
let b = String::from("xyz");
longest(&a, &b)
};
println!("{result}");
}It does not compile
- Expecting
long stringbecauseresultwould point ata: the compiler checks only the signature, which lets the result borrow fromb, so it may not outliveb(E0597). - Expecting the shorter string
xyz:'abounds how long the result stays valid, not which argumentlongestreturns.
- How would you move one line so that the program compiles and prints
long string? - How would the signature change if
longestalways returnedx?