Member-only story
Cell<T> and RefCell<T> — Wrapper Types in Rust In Depth with Examples
In the last post, we saw that Box Pointer as a unique smart pointer that can be used to initialize values on the heap or of unknown size. In this post, we’ll take a look at Cell and RefCell
wrapper types , how to use them and more importantly how not to use them. Both Cell and RefCell in rust act as a Container type that allow interior mutability. These are types that kind of skip borrow checking, and can prove dangerous when not used properly at runtime. Let’s take a look at what this really means by looking at interior mutability.
Interior mutability
Rust takes mutability very seriously. Ownership rules prevent developers from doing something that may have side effects. For most basic operations, we can only mutate a value when we explicitly declare a variable as mutable. And then the compiler performs checks to ensure we don’t violate any ownership and mutability rules.
Often times you may want to mutate values without explicitly taking a mutable reference. These are the cases when Cell
and RefCell
types come in handy.
A Cell<T>
or RefCell<T>
type in rust is a container that allows developers to have shared mutability of the any underlying variable. Let’s take a look at the sample below.
use std::cell::Cell…