Rust 函数中的可变寿命qs

Rust 函数中的可变寿命qs,rust,lifetime,Rust,Lifetime,调用get_str3时,它也有一个编译错误: 错误[E0597]:`tmp`的寿命不够长 ->src/main.rs:13:22 | 13 |设x:&'a str=tmp.as|u str; |^^^借来的价值活得不够长 14 |返回x; 15 | } |-借来的价值仅在此处有效 | 注意:借用值必须在11:1的函数体上定义的生命周期“a”内有效。。。 ->src/main.rs:11:1 | 11 | fn get_str3第一个函数起作用,因为字符串具有“静态生存期”,并且将由编译器提升 至

调用get_str3时,它也有一个编译错误:

错误[E0597]:`tmp`的寿命不够长 ->src/main.rs:13:22 | 13 |设x:&'a str=tmp.as|u str; |^^^借来的价值活得不够长 14 |返回x; 15 | } |-借来的价值仅在此处有效 | 注意:借用值必须在11:1的函数体上定义的生命周期“a”内有效。。。 ->src/main.rs:11:1 |
11 | fn get_str3第一个函数起作用,因为字符串具有“静态生存期”,并且将由编译器提升

至于其他的

fn get_str1<'a>() -> &'a str {
    let x = "hello";
    return x;
}

fn get_str2<'a>(str1: &str) -> &'a str {
    let x: &'a str = (str1.to_string() + "123").as_str();
    return x;
}

fn get_str3<'a>(str1: &str) -> &'a str {
    let tmp = str1.to_string() + "123";
    let x: &'a str = tmp.as_str();
    return x;
}

#[test]
fn lifetime_test() {
    println!("{}", get_str1());
    println!("{}", get_str2("hello"));
    println!("{}", get_str3("hello"))
}
阅读上面的每一条注释,很明显您实际上是在试图返回对本地字符串的引用。您不能这样做,因为字符串将在函数末尾被销毁,并且引用将无效

这也适用于第三个函数。您将返回对字符串实例的引用,该实例将在函数结束时销毁

fn get_str2<'a>(str1: &str) -> &'a str {
    let x = (str1.to_string() + "123").as_str();
    return x
}
let x = str1.to_string(); // this is of type String, and its lifetime is local to this function
let y = str1 + "123"; // This consumes str1 and appends a &str to it - thus the lifetime is still of the new String instance above
let z = y.as_str(); // This returns a reference to the local String instance