Magyar oldal English site

Site map
2024-10-20 19:31:34 (Originally published at: 2024-10-20)

Rc<RefCell<T>> is a trap in Rust

In Rust in order to have a shared mutable access to an object, it's tempting to create a Rc<RefCell<T>> object to hold the object. However in order to call a method on T, you need to borrow the RefCell contained in the Rc, and this borrow remains active while the method is running even if you don't strictly need it for the whole time. If the Refcell is attempted to be borrowed again through a different Rc while the method is running, you will have a panic. This is an issue that's easy to run into, because whole point of embedding a RefCell into an Rc is to have shared access. But you don't really have it.

So instead of using your whole struct through a RefCell, you should protect each of the fields of it with a RefCell, so you can use interior mutability to limit access. This way your methods can take an immutable &self reference instead of mutable, such that you can access your object through a plain Rc multiple times without worrying about panics.

If you want to discuss this post, share it on social media.
Recently updated:

RSS

Logo