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 },
}
}
To expand on Chris' answer, there are two issues to solve:
It is relatively easy to cover (1), a simple
&self.a
could be used for example, anchoringself
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 thatself.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.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
.