What time to live to use for internal references to fields in structures?
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 Vec<u32>
and replacing element_ptr
with a pointer reference to the largest element of the array.)
How can I write this code in safe rust i.e. using a link instead of a raw pointer? Here's what I've 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 won't 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 it possible to correctly express the life time element_ref
?
+3
source to share
No one has answered this question yet
See similar questions:
or similar: