Text of rust.docs.kernel.org › src › core › cell.rs.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

cell.rs - source

Skip to main content core/ cell.rs 1 //! Shareable mutable containers. 2 //! 3 //! Rust memory safety is based on this rule: Given an object `T`, it is only possible to 4 //! have one of the following: 5 //! 6 //! - Several immutable references (`&T`) to the object (also known as **aliasing**). 7 //! - One mutable reference (`&mut T`) to the object (also known as **mutability**). 8 //! 9 //! This is enforced by the Rust compiler.

However, there are situations where this rule is not 10 //! flexible enough. Sometimes it is required to have multiple references to an object and yet 11 //! mutate it. 12 //! 13 //! Shareable mutable containers exist to permit mutability in a controlled manner, even in the 14 //! presence of aliasing. [`Cell<T>`], [`RefCell<T>`], and [`OnceCell<T>`] allow doing this in 15 //! a single-threaded way—they do not implement [`Sync`]. (If you need to do aliasing and 16 //! mutation among multiple threads, [`Mutex<T>`], [`RwLock<T>`], [`OnceLock<T>`] or [`atomic`] 17 //! types are the correct data structures to do so).

18 //! 19 //! Values of the `Cell<T>`, `RefCell<T>`, and `OnceCell<T>` types may be mutated through shared 20 //! references (i.e. the common `&T` type), whereas most Rust types can only be mutated through 21 //! unique (`&mut T`) references. We say these cell types provide 'interior mutability' 22 //! (mutable via `&T`), in contrast with typical Rust types that exhibit 'inherited mutability' 23 //! (mutable only via `&mut T`).

24 //! 25 //! Cell types come in four flavors: `Cell<T>`, `RefCell<T>`, `OnceCell<T>`, and `LazyCell<T>`. 26 //! Each provides a different way of providing safe interior mutability. 27 //! 28 //! ## `Cell<T>` 29 //! 30 //! [`Cell<T>`] implements interior mutability by moving values in and out of the cell. That is, a 31 //! `&T` to the inner value can never be obtained, and the value itself cannot be directly 32 //! obtained without replacing it with something else.

This type provides the following 33 //! methods: 34 //! 35 //! - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current 36 //! interior value by duplicating it. 37 //! - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current 38 //! interior value with [`Default::default()`] and returns the replaced value. 39 //! - All types have: 40 //! - [`replace`](Cell::replace): replaces the current interior value and returns the replaced 41 //! value.

42 //! - [`into_inner`](Cell::into_inner): this method consumes the `Cell<T>` and returns the 43 //! interior value. 44 //! - [`set`](Cell::set): this method replaces the interior value, dropping the replaced value. 45 //! 46 //! `Cell<T>` is typically used for more simple types where copying or moving values isn't too 47 //! resource intensive (e.g. numbers), and should usually be preferred over other cell types when 48 //! possible.

For larger and non-copy types, `RefCell` provides some advantages. 49 //! 50 //! ## `RefCell<T>` 51 //! 52 //! [`RefCell<T>`] uses Rust's lifetimes to implement "dynamic borrowing", a process whereby one can 53 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are 54 //! tracked at _runtime_, unlike Rust's native reference types which are entirely tracked 55 //! statically, at compile time.

56 //! 57 //! An immutable reference to a `RefCell`'s inner value (`&T`) can be obtained with 58 //! [`borrow`](`RefCell::borrow`), and a mutable borrow (`&mut T`) can be obtained with 59 //! [`borrow_mut`](`RefCell::borrow_mut`). When these functions are called, they first verify that 60 //! Rust's borrow rules will be satisfied: any number of immutable borrows are allowed or a 61 //! single mutable borrow is allowed, but never both.

If a borrow is attempted that would violate 62 //! these rules, the thread will panic. 63 //! 64 //! The corresponding [`Sync`] version of `RefCell<T>` is [`RwLock<T>`]. 65 //! 66 //! ## `OnceCell<T>` 67 //! 68 //! [`OnceCell<T>`] is somewhat of a hybrid of `Cell` and `RefCell` that works for values that 69 //! typically only need to be set once. This means that a reference `&T` can be obtained without 70 //! moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike 71 //! `RefCell`).

However, once set, its value cannot be updated unless you have a mutable 72 //! reference to the `OnceCell`. 73 //! 74 //! `OnceCell` provides the following methods: 75 //! 76 //! - [`get`](OnceCell::get): obtain a reference to the inner value 77 //! - [`set`](OnceCell::set): set the inner value if it is unset (returns a `Result`) 78 //! - [`get_or_init`](OnceCell::get_or_init): return the inner value, initializing it if needed 79 //! - [`get_mut`](OnceCell::get_mut): provide a mutable reference to the inner value, only available 80 //! if you have a mutable reference to the cell itself.

81 //! 82 //! The corresponding [`Sync`] version of `OnceCell<T>` is [`OnceLock<T>`]. 83 //! 84 //! ## `LazyCell<T, F>` 85 //! 86 //! A common pattern with OnceCell is, for a given OnceCell, to use the same function on every 87 //! call to [`OnceCell::get_or_init`] with that cell. This is what is offered by [`LazyCell`], 88 //! which pairs cells of `T` with functions of `F`, and always calls `F` before it yields `&T`.

89 //! This happens implicitly by simply attempting to dereference the LazyCell to get its contents, 90 //! so its use is much more transparent with a place which has been initialized by a constant. 91 //! 92 //! More complicated patterns that don't fit this description can be built on `OnceCell<T>` instead. 93 //! 94 //! `LazyCell` works by providing an implementation of `impl Deref` that calls the function, 95 //! so you can just use it by dereference (e.g. `*lazy_cell` or `lazy_cell.deref()`).

96 //! 97 //! The corresponding [`Sync`] version of `LazyCell<T, F>` is [`LazyLock<T, F>`]. 98 //! 99 //! # When to choose interior mutability 100 //! 101 //! The more common inherited mutability, where one must have unique access to mutate a value, is 102 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing, 103 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and 104 //! interior mutability is something of a last resort.

Since cell types enable mutation where it 105 //! would otherwise be disallowed though, there are occasions when interior mutability might be 106 //! appropriate, or even *must* be used, e.g. 107 //! 108 //! * Introducing mutability 'inside' of something immutable 109 //! * Implementation details of logically-immutable methods. 110 //! * Mutating implementations of [`Clone`]. 111 //! 112 //! ## Introducing mutability 'inside' of something immutable 113 //!

114 //! Many shared smart pointer types, including [`Rc<T>`] and [`Arc<T>`], provide containers that can 115 //! be cloned and shared between multiple parties. Because the contained values may be 116 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be 117 //! impossible to mutate data inside of these smart pointers at all. 118 //! 119 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce 120 //! mutability: 121 //!

122 //! ``` 123 //! use std::cell::{RefCell, RefMut}; 124 //! use std::collections::HashMap; 125 //! use std::rc::Rc; 126 //! 127 //! fn main() { 128 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); 129 //! // Create a new block to limit the scope of the dynamic borrow 130 //! { 131 //! let mut map: RefMut<'_, _> = shared_map.borrow_mut(); 132 //! map.insert("africa", 92388); 133 //! map.insert("kyoto", 11837); 134 //! map.insert("piccadilly", 11826); 135 //! map.insert("marbles", 38); 136 //! } 137 //!

138 //! // Note that if we had not let the previous borrow of the cache fall out 139 //! // of scope then the subsequent borrow would cause a dynamic thread panic.

The rest of this page is on the live site.