Why is there `RefCell::get_mut` to get a compile-time checked `&mut T`, but not `get_ref`?

I'm storing some data in a RefCell, but most of the time a compile-time checked &mut T or &T would be ideal.

To get a compile-time checked &mut T, there is get_mut (which requires mutable access to the RefCell).

However, I just realized, there is no get_ref equivalent.

Is there a different way to get a statically checked &T out of a RefCell, that I don't see?

I don't have mutable access to the RefCell where the compile-time checked &T is needed (otherwise I could "downgrade" &mut T to &T, I think), and I'd like to avoid RefCell::borrow, if possible.

If this isn't possible: Why is there a way to get a compile-time checked &mut T, but not a compile-time checked &T?

It's not possible

Because &mut T doesn't mean mutable reference to T, it means exclusive reference to T. Similarly &T doesn't mean immutable reference to T, it means shared reference to T. You can read more here:

https://limpet.net/mbrubeck/2019/02/07/rust-a-unique-perspective.html

1 Like

You would be able to call borrow_mut at same time as having the reference from such a call. Breaking the borrow rules.

1 Like

Thanks, @RustyYato and @jonh! That makes, unfortunately, sense.

Now I need to continue to think about how to overcome my problem differently... :laughing:

But I have already an idea, that might work... :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.