我正在从使用rust 的书中了解生命周期。
一个简单的问题,
以下代码给出了正确的预期错误:
fn check_check() {
let r;
{
let s = String::from("s");
r = check(&s); // says s does not live long enough
}
println!("{}", r);
}
fn check<'a>(s: &'a str) -> &'a str {
return s;
}
这是因为我已经提到检查函数中的生命周期与参数相同。所以这很好,我理解。
按照同样的逻辑,当我编写这段代码时,不会出现任何错误。
这是我不明白的事情,这是如何能够编译的?
fn check_check() {
let r;
{
let s = "a";
r = check(&s); // works just fine, why? and how?
}
println!("{}", r);
}
fn check<'a>(s: &'a str) -> &'a str {
return s;
}
最佳答案
在我们问生命周期之前,这里有一个关于类型的问题:字符串文字的类型是 &'static str
,当你引用它时,你会得到 &&' static str
(两个引用),那么如何将它传递给需要 &str
(一个引用)的函数?
答案是,当将参数传递给函数时,编译器可能会进行强制调整;可能的调整之一是解引用强制,它解引用传递的值。因此,我们采用 &&'static str
并取消引用它以获取 &'static str
。
这也是您问题的答案:由于我们传递 &'static str
,'a
是 'static
,所以它确实活得足够长。
关于str 和 String 的 Rust 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76400310/