// Function with explicit lifetimes // This function takes two string slices and returns the longer one. // The 'a lifetime parameter ensures that the returned reference does not outlive // the shortest-lived of the two input references. fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } // Struct holding a reference with a lifetime // This ensures that the 'part' reference inside ImportantExcerpt // does not outlive the string it refers to. struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &'a str { println!("Attention: {}", announcement); self.part } } fn main() { let string1 = String::from("long string is long"); let result; { let string2 = String::from("xyz"); result = longest(string1.as_str(), string2.as_str()); println!("The longest string is {}", result); } // println!("The longest string is {}", result); // This would compile error if string2 was passed in this scope due to lifetime rules let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; println!("Excerpt part: {}", i.part); let part_ref = i.announce_and_return_part("Important notice!"); println!("Returned part_ref: {}", part_ref); }