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 A
s, xs
, and a vector of B
s, 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 B
s 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
C
owns all the
data. -
A
s are just "somewhere in the heap", instead of being stored nicely
side by side in a particular vector. -
I cannot make my
C
type 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 A
s and a vector of
A
-referencing B
s?