lifetimes1.rs (699B)
1 // The Rust compiler needs to know how to check whether supplied references are 2 // valid, so that it can let the programmer know if a reference is at risk of 3 // going out of scope before it is used. Remember, references are borrows and do 4 // not own their own data. What if their owner goes out of scope? 5 6 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { 7 // ^^^^ ^^ ^^ ^^ 8 if x.len() > y.len() { x } else { y } 9 } 10 11 fn main() { 12 // You can optionally experiment here. 13 } 14 15 #[cfg(test)] 16 mod tests { 17 use super::*; 18 19 #[test] 20 fn test_longest() { 21 assert_eq!(longest("abcd", "123"), "abcd"); 22 assert_eq!(longest("abc", "1234"), "1234"); 23 } 24 }