Smart Pointers · 19 min · free with an account

Rc & RefCell

Lesson preview · about 30%

Rc shares ownership; RefCell moves the borrow check to runtime.

Core idea

RefCell moves the borrow rules to runtime; breaking them panics.

Start with the idea

Rc<T> keeps a count and frees when it reaches zero, but only hands out shared references. Pairing it with RefCell<T> lets you mutate through that shared handle, with the borrow rules checked at runtime instead — a violation panics rather than failing to compile. Neither is thread-safe; that is Arc and Mutex.

Rc<T> provides shared ownership within one thread. Each clone of an Rc is another strong handle to the same allocation, not a deep copy of T. The allocation is released when its last strong owner disappears. Because multiple owners can access the same value, Rc<T> normally provides shared read access. Wrapping the value in RefCell<T> permits mutation by checking the borrow rule at runtime.

In the sample, both shared and second refer to the same cell.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Cargo & Real Projects