So, Rc
makes sure that SomeStruct
is accessible by many people at the same time. But how do I access?
By dereferencing. If you have a variable x
of type Rc<...>
, you can access the inner value using *x
. In many cases this happens implicitly; for example you can call methods on x
simply with x.method(...)
.
I only see the get_mut
method, which returns a mutable reference. But the text explained that "Rc
allows only immutable borrows".
The get_mut()
method is probably more recent than the explanation stating that Rc
only allows immutable borrows. Moreover, it only returns a mutable borrow if there currently is only a single owner of the inner value, i.e. if you currently wouldn't need Rc
in the first place. As soon as there are multiple owners, get_mut()
will return None
.
If it's possible to access Rc
's object in mut and not mut way, why a RefCell
is needed?
RefCell
will allow you to get mutable access even when multiple owners exist, and even if you only hold a shared reference to the RefCell
. It will dynamically check at runtime that only a single mutable reference exists at any given time, and it will panic if you request a second, concurrent one (or return and error for the try_borrow
methods, respecitvely). This functionality is not offered by Rc
.
So in summary, Rc
gives you shared ownership. The innervalue has multiple owners, and reference counting makes sure the data stays alive as long as at least one owner still holds onto it. This is useful if your data doesn't have a clear single owner. RefCell
gives you interior mutability, i.e. you can borrow the inner value dynamically at runtime, and modify it even with a shared reference. The combination Rc<RefCell<...>>
gives you the combination of both – a value with multiple owners that can be borrowed mutably by any one of the owners.
For further details, you can read the relevant chapters of the Rust book:
Rc
." This is appropriately qualified with "generally", so I think it's fine. – Sven MarnachRc
, it's true in most practical cases, so making this more correct may make it more confusing in other respects. – Sven Marnach