[英]Why does the compiler assume the returned reference has the same lifetime as the struct?
I have the following Rust code:我有以下 Rust 代码:
pub struct Foo {}
impl Foo {
fn bar(&self) -> &[u8] {
// obtain some pointer from FFI and return it as a slice (ignore the zeros)
unsafe { std::slice::from_raw_parts(0 as *const u8, 0) }
}
}
fn main() {
let a;
{
let b = Foo {};
a = b.bar();
}
a;
}
When compiling, the following error is produced:编译时,会产生以下错误:
error[E0597]: `b` does not live long enough
--> src/main.rs:14:13
|
14 | a = b.bar();
| ^ borrowed value does not live long enough
15 | }
| - `b` dropped here while still borrowed
16 | a;
| - borrow later used here
This is the outcome I would expect;这是我所期望的结果; The compiler won't let a reference to some object (from FFI in my case) outlive its container.编译器不会让对某些 object(在我的例子中来自 FFI)的引用超过其容器。 However, I am confused as to why this is.但是,我很困惑为什么会这样。 Why does the compiler assume that the returned reference should have the same lifetime as the struct?为什么编译器假定返回的引用应该与结构具有相同的生命周期? For all it knows, the returned reference could be freed at any time.据它所知,返回的引用可以随时释放。
Due to lifetime elision , you don't have to annotate every reference with lifetimes if the compiler can figure it out.由于生命周期省略,如果编译器可以弄清楚,您不必用生命周期注释每个引用。 However, you should know it exists so that you know when you write:但是,您应该知道它的存在,以便您在编写时知道:
fn bar(&self) -> &[u8]
The compiler deduces it as:编译器将其推断为:
fn bar<'a>(&'a self) -> &'a [u8]
So the slice from b.bar()
is bound to lifetime of b
.所以b.bar()
的切片绑定到b
的生命周期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.