Values, Text and Callbacks · 14 min · free with an account

Cell, RefCell and Runtime Borrows

Lesson preview · about 30%

Interior mutability changes how access is checked; it does not remove the safety contract.

Core idea

Runtime borrow checking still enforces exclusivity; ownership transfer and concurrent sharing have different trait bounds.

Start with the idea

Cell<T> is useful when a value can be read or replaced through a shared reference without handing out a reference to its contents. RefCell<T> instead hands out guarded borrows and checks their exclusivity at runtime. borrow_mut can panic on a conflict; try_borrow_mut lets you handle that conflict as an error. The example retains a reader, observes a rejected writer, then drops the reader and mutates successfully.

Neither type automatically supplies synchronized shared access between threads. RefCell<T> can be Send when T is Send, but it is not Sync: transferring a uniquely owned cell is different from sharing references to it concurrently.

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 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep