As far as I can tell, the only way to do this safely is with Rc
and friends.
struct MyStruct {
x: Rc<int>,
storage: Vec<Rc<int>>
}
If you want to get mutable references to the data you will have to use an abstraction like RefCell
, which will check that you are not violating Rust’s invariants dynamically:
struct MyStruct {
x: Rc<RefCell<int>>,
storage: Vec<Rc<RefCell<int>>>
}
The proposed 'self
lifetime for contained pointers only upholds one aspect of Rust’s rules: & and &mut references cannot be NULL. However, it does not allow for upholding the other invariants relating to borrowing and mutability.
If you need a struct which actually has to refer to itself (not into itself) then you can do something similar:
struct MyStruct {
val: int
self: Option<Rc<RefCell<MyStruct>>>
}
impl MyStruct {
fn new(val: int) -> Rc<RefCell<MyStruct>> {
let mut this = Rc::new(RefCell::new(MyStruct { val: val, self: None }));
this.borrow_mut().self = Some(self.clone());
this
}
}