I'd like to have a struct which references another with the reference being a field member. The struct doesn't own the data it's referring to, and the data can be non-existent. Is this the only way of expressing what I'm after?
pub struct MyStruct {
pub data: Weak<Option<RefCell<Data>>>
}
The lifetime of the data member should always at least match the struct in scenarios where it's needed, so maybe just a regular Option<&'a mut Data>
could work? In that case, how would I get a &Data
out of the option if necessary? Sometimes I want the data not to be mut
.
This works for temporary borrowing of Data
, but will prevent mutation of Data
as long as that struct exists. This is sometimes called a "view struct" and is normally short-lived.
If you don't want to borrow it until you need it, then using Rc makes sense.
Yeah, that makes sense, since it would be a double borrow. I guess I'm stuck with using Rc for now.
Yeah, it would be a conflicting borrow, because mutation needs exclusive access. It wouldn't be conflicting if both borrows were shared (&
).
You probably want to make it a Weak<
(possibly deallocated) RefCell<
(inner-mutable) Option<
(possibly not-existent) Data
, however. The type you've described won't allow you to track any changes in the original struct
if it ever goes from Some(data)
to None
and vice versa.
Depending on the details, you might be able to get away with Option<&'a RefCell<Data>>
, which would save you from the extra heap allocation at the expense of flexibility (because of the lifetime constraints).
3 Likes
True, thanks for pointing that out!
I think you could get ride of the Option and use Weak::new() for the non-existent case.
2 Likes