pub fn understand_lifetime()
Expand description
理解普通生命周期参数:
说明: 生命周期参数:late bound vs early bound
示例1:
fn return_str<'a>() -> &'a str {
let mut s = "Rust".to_string();
for i in 0..3 {
s.push_str("Good ");
}
&s[..] //"Rust Good Good Good"
}
fn main() {
let x = return_str();
}
示例2:
fn foo<'a>(x: &'a str, y: &'a str) -> &'a str {
let result = String::from("really long string");
// error
result.as_str()
}
fn main() {
let x = "hello";
let y = "rust";
foo(x, y);
}
示例3:
fn the_longest(s1: &str, s2: &str) -> &str {
if s1.len() > s2.len() { s1 } else { s2 }
}
fn main() {
let s1 = String::from("Rust");
let s1_r = &s1;
{
let s2 = String::from("C");
let res = the_longest(s1_r, &s2);
println!("{} is the longest", res);
}
示例4: