Is there a nice way to represent an optional, non-owning reference?

⚓ rust    📅 2025-05-22    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

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.

6 posts - 4 participants

Read full topic

🏷️ rust_feed