How do I borrow a RefCell, find a key, and return a reference to the result? [duplicate]

When you borrow from a RefCell, the reference you get has a shorter lifetime than the RefCell‘s. That’s because the reference’s lifetime is restricted by the guard returned by borrow(). That guard ensures that nobody else can take a mutable reference to the value until the guard is dropped. However, you are trying to return … Read more

How do I return a reference to something inside a RefCell without breaking encapsulation?

You can create a new struct similar to the Ref<‘a,T> guard returned by RefCell::borrow(), in order to wrap this Ref and avoid having it going out of scope, like this: use std::cell::Ref; struct FooGuard<‘a> { guard: Ref<‘a, MutableInterior>, } then, you can implement the Deref trait for it, so that it can be used as … Read more

tech