Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading