# Self-referencing structs

**URL:** https://internals.rust-lang.org/t/self-referencing-structs/418
**Category:** ideas (deprecated)
**Created:** [August 21, 2014, 3:10pm UTC](https://internals.rust-lang.org/t/self-referencing-structs/418 "2014-08-21T15:10:43Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![reem](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/reem/32/167_2.png) [@reem](https://internals.rust-lang.org/u/reem)
#### Post date: [September 6, 2014, 2:58pm UTC](https://internals.rust-lang.org/t/self-referencing-structs/418/3 "2014-09-06T14:58:58Z")

</div>

As far as I can tell, the only way to do this safely is with `Rc` and friends.

```rust
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:

```rust
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:

```rust
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
    }
}

```

---

_[View the full topic](https://internals.rust-lang.org/t/self-referencing-structs/418)._
