Home
Blog
Understanding RefCell in Rust
Updated
Dot Net Perls

Understanding RefCell in Rust

There are many aspects to the Rust language that are hard to understand at first. Consider the RefCell struct. This gives us "interior mutability"—but what is that, and why do we need it? Suppose we have a struct, and we pass the struct as an immutable reference throughout our program.

Many parts of our program might use the struct, mostly reading from it. Occasionally, a change to the data in the RefCell is needed. By calling borrow or borrow_mut we can get read access or exclusive write access. RefCell tracks at runtime whether calling borrow or borrow_mut should succeed—if no other uses are active in the program, it will allow the calls.

Some advantages to RefCell include:

It allows any number of reads, but only one active borrow_mut (write).
It allows us to mutate data through an immutable reference.
We can avoid using mut references everywhere as arguments.

For threads, the RwLock struct is the same as RefCell (which cannot be used across threads). Basically the point of RefCell, then, is that we can safely modify a field through an immutable struct reference.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen