Member-only story

Cell<T> and RefCell<T> — Wrapper Types in Rust In Depth with Examples

Shanmukh Sista
6 min readApr 6, 2023
Photo by Richard Horvath on Unsplash

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 RefCellwrapper 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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response