Reputation: 23
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.
Upvotes: 1
Views: 547
Reputation: 6120
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.
Upvotes: 2