lifetimes2.rs (1016B)
1 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { 2 if x.len() > y.len() { x } else { y } 3 } 4 5 fn main() { 6 let string1 = String::from("long string is long"); 7 // Solution1: You can move `strings2` out of the inner block so that it is 8 // not dropped before the print statement. 9 let string2 = String::from("xyz"); 10 let result; 11 { 12 result = longest(&string1, &string2); 13 } 14 println!("The longest string is '{result}'"); 15 // `string2` dropped at the end of the function. 16 17 // ========================================================================= 18 19 let string1 = String::from("long string is long"); 20 let result; 21 { 22 let string2 = String::from("xyz"); 23 result = longest(&string1, &string2); 24 // Solution2: You can move the print statement into the inner block so 25 // that it is executed before `string2` is dropped. 26 println!("The longest string is '{result}'"); 27 // `string2` dropped here (end of the inner scope). 28 } 29 }