How can I provide a reference to a sibling struct?
I have a structure with some public immutable data, and another structure that uses this data. I would like to combine them into one structure, because they combine logical meaning. 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's answer, two problems need to be addressed:
- have a syntax that uniquely allows you to refer to a relative
- to make sure that the borrowing rules can still be checked.
It is relatively easy to cover (1), for example a simple &self.a
one could be used self
in the outermost type; however, it seems that cover (2) would be much more complicated: nothing in the structure itself indicates this relationship, and therefore it is not obvious what is self.a
borrowed.
Without self.a
marked as borrowed, you are exposed to a lot of unsafe behaviors, such as possible destructive behavior that Rust is designed to avoid.
It simply cannot be imagined in secure Rust code.
In such cases, you might need to dynamically borrow with things like RefCell
.