Hello!
I have a question regarding the rust ownership system. Suppose I have an A struct,
struct A {
...
}
and a B struct, which references an A:
strict B<'a> {
a: &'a A
}
I can create vector of As, xs, and a vector of Bs, ys, like this:
let mut xs = Vec::new();
xs.push(A::new(...));
let mut ys = Vec::new();
ys.push(B::new(&xs[0],...));
vector bs is larger and many Bs use a reference to the same A.
So far so good, but I would like to create a struct C, which holds both
vectors, like this:
struct C {
xs: Vec<A>,
ys: Vec<B<?>> // this Bs use As from ys
}
The problem is, I don't know what lifetime to use for B, because it's not
'static, and C should not have any lifetime parameters, because it owns all data.
The pointer structure in this setup looks reasonable: no cycles or mutable refs,
but I can't write code that creates it.
At the moment, I work around the problem by having B hold an Rc<A>, but I
really don't like the solution:
-
It fails to represent the implied ownership model, that
Cowns all the
data. -
As are just "somewhere in the heap", instead of being stored nicely
side by side in a particular vector. -
I cannot make my
Ctype sync because ofRc(I can useArc, but again,
it looks like a solution to the wrong problem)
So, how can I create such a sturct C, that owns a vector of As and a vector of
A-referencing Bs?