Reputation: 461
I have the following Rust code:
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. 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.
Upvotes: 1
Views: 54
Reputation: 59817
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
.
Upvotes: 3