rustinterior-mutability

How to convert RefMut<T> to Ref<T>


I was wondering if it's possible to convert a RefMut<T> to a Ref<T> in Rust?

Some context - Inside of a function, I've used .borrow_mut() to access an item in a RefCell<T> mutably, and now want to return an immutable reference to it from the function. I believe I cannot use &T as it would be a temporary value than cannot be returned from the function, though correct me if I'm wrong.

If not, I'd love to know the technical reason why it's not possible.


Solution

  • If you just want to prevent mutation through RefMut you can give a reference to it, which will "turn off" DerefeMut implementation (you won't have access to exclusive reference).

    But if you want to "convert" RefMut to Ref, then I'm afraid it's not possible. The only way is to drop RefMut and then borrow again. I don't think this is impossible pre se. You could imagine a method on RefMut that would change reference counters and downgrade a RefMut to Ref. But there is nothing like this in current standard library.