3

I have a structure with some shared immutable data, and another structure that makes use of that data. I'd like to bundle these into one structure because they make logical sense together. However, I don't understand how I can provide a reference to the object itself during construction:

struct A {
    v: i32,
}
struct B<'a> {
    a: &'a A,
    b: i32,
}

struct C<'a> {
    a: A,
    b: B<'a>,
}

fn main() {
    C {
        a: A { v: 13 },
        b: B { a: &??, b: 17 },
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

2 Answers2

4

To expand on Chris' answer, there are two issues to solve:

  1. have a syntax that unambiguously allows referring to a sibling
  2. make it so that borrowing rules can still be verified

It is relatively easy to cover (1), a simple &self.a could be used for example, anchoring self in the most outer type possible; however it seems that covering (2) would be much more difficult: nothing in the structure itself points to this relationship, and therefore it is not evident that self.a is borrowed.

Without self.a being marked as borrowed, you run into plenty of unsafe behaviors, such as possible destructive behaviors, which Rust is designed to stay clear of.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
3

This simply cannot be represented in safe Rust code.

In cases like this, you may need to resort to dynamic borrowing with things like RefCell.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • I've used RefCell, but could you add a small example of how I would use it in this case? Would I need to rewrite `B` to take advantage of this? If so, what if `B` were provided by an external source? – Shepmaster Oct 14 '14 at 12:16