结构中用于内部字段引用的生命周期是多少?

时间:2015-06-27 20:46:34

标签: rust lifetime

使用原始指针考虑以下Rust代码:

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
}

(在这个最小的例子中有点傻,但你可以想象用element替换Vec<u32>并用引用指向数组最大元素的指针替换element_ptr 。)

如何在安全生锈中编写此代码,即使用引用而不是原始指针?这是我试过的:

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;

不出所料,这无法编译:

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

有没有办法可以正确表达element_ref的生命周期?

0 个答案:

没有答案