Consider the following Rust code, using raw pointers:
struct InteriorPointer {
element: Box<u32>,
element_ptr: *const u32,
}
fn mk_interior_pointer() -> InteriorPointer {
let mut result = InteriorPointer{
element: Box::new(1u32),
element_ptr: std::ptr::null(),
};
result.element_ptr = &*result.element as *const u32;
result
}
(It's a bit silly in this minimal example, but you could imagine replacing element
with a Vec<u32>
and replacing element_ptr
with a reference to the pointer to the largest element of the array.)
How can I write this code in safe rust, i.e. using a reference instead of a raw pointer? Here's what I tried:
struct InteriorPointer {
element: Box<u32>,
element_ref: &'static u32,
// I actually want to say something like "&'self u32" or
// "&'lifetimeof(element) u32" but I'm not allowed.
}
fn mk_interior_pointer() -> InteriorPointer {
let mut result = InteriorPointer{
element: Box::new(1u32),
element_ref: &dummy_element,
};
result.element_ref = &*result.element;
result
}
static dummy_element: u32 = 5;
Unsurprisingly, this fails to compile:
src/lib.rs:11:25: 11:40 error: `*result.element` does not live long enough
src/lib.rs:11 result.element_ref = &*result.element;
^~~~~~~~~~~~~~~
note: reference must be valid for the static lifetime...
src/lib.rs:10:5: 13:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 10:4
Is there a way I can express the lifetime of element_ref
correctly?