2021年3月12日星期五

Returning reference from impl

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:13:13  |  13 |         a = b.bar();  |             ^ borrowed value does not live long enough  14 |     }  |     - `b` dropped here while still borrowed  15 |     a;  |     - borrow later used here    error: aborting due to previous error    For more information about this error, try `rustc --explain E0597`.  

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.

https://stackoverflow.com/questions/66610032/returning-reference-from-impl March 13, 2021 at 12:06PM

没有评论:

发表评论