use std::fmt::Display; fn main() { // { // let r; // { // let x = 5; // r = &x; // 报错 // } // // 当使用r的时候,r引用的x已经离开作用域失效 // println!("r: {}", r); // } // 修改方案,被引用的x必须生命周期比引用者r长 let x = 5; let r = &x; println!("r: {}", r); fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } let string1 = String::from("aaaa"); let string2 = "sss"; let result = longest(string1.as_str(), string2); println!("the longest string is {}", result); // 悬垂引用例子 // fn dailing_reference<'a>() -> &'a str { // let result = String::from("vvv"); // result.as_str() // } // struct生命周期标注 struct ImportantExcerpt<'a> { part: &'a str, } let novel = String::from("call me ishmael. Some years age ..."); let first_sentence = novel.split('.').next().expect("Could not found a '.'"); let i = ImportantExcerpt { part: first_sentence, }; // 生命周期的省略 fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } // 泛型参数类型、trait bound、生命周期 fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str where T: Display, { println!("Announcement! {}", ann); if x.len() > y.len() { x } else { y } } }