Is it possible to have a short-lived Rust ref that returns None if the object has been deconstructed?

Viewed 44

Could I have something such as

struct LongLivedStruct { // lasts for a long time
    possibleRef: ShortLivedRc<SomeTrait> // SomeTrait will be freed soon
}

such that I can try to dereference it later:

impl LongLivedStruct  {
    fn try_to_do_something(&self) -> &str {
        match &self.possibleRef.try_deref() {
            Ok(_) => "Value still exists, we can do something with it!"
            Err(_) => "Value has already been deconstructed"
        }
    }
}

without it panicking if it no longer exists?

1 Answers

It looks to me like you can do that with a Weak reference.

You can create a weak reference to store in your LongLivedStruct by calling Rc::downgrade on an Rc with your SomeTrait object and store it in your LongLivedStruct.

Then you can get it back by calling Weak::upgrade on it to get an Option<Rc<SomeTrait>> back.

Related