Skip to content

Commit d1b28b7

Browse files
committed
Documentation updates to better share the purpose of OnceCell/OnceLock
1 parent dc4ba57 commit d1b28b7

File tree

3 files changed

+76
-28
lines changed

3 files changed

+76
-28
lines changed

library/core/src/cell.rs

+68-25
Original file line numberDiff line numberDiff line change
@@ -11,36 +11,77 @@
1111
//! mutate it.
1212
//!
1313
//! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
14-
//! presence of aliasing. Both [`Cell<T>`] and [`RefCell<T>`] allow doing this in a single-threaded
15-
//! way. However, neither `Cell<T>` nor `RefCell<T>` are thread safe (they do not implement
16-
//! [`Sync`]). If you need to do aliasing and mutation between multiple threads it is possible to
17-
//! use [`Mutex<T>`], [`RwLock<T>`] or [`atomic`] types.
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).
1818
//!
19-
//! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
20-
//! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
21-
//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
22-
//! with typical Rust types that exhibit 'inherited mutability'.
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`).
2324
//!
24-
//! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
25-
//! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
26-
//! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
27-
//! methods to retrieve and change the current interior value:
25+
//! Cell types come in three flavors: `Cell<T>`, `RefCell<T>`, and `OnceCell<T>`. Each provides
26+
//! 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, an
31+
//! `&mut T` to the inner value can never be obtained, and the value itself cannot be directly
32+
//! obtained without replacing it with something else. Both of these rules ensure that there is
33+
//! never more than one reference pointing to the inner value. This type provides the following
34+
//! methods:
2835
//!
2936
//! - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current
30-
//! interior value.
37+
//! interior value by duplicating it.
3138
//! - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current
3239
//! interior value with [`Default::default()`] and returns the replaced value.
33-
//! - For all types, the [`replace`](Cell::replace) method replaces the current interior value and
34-
//! returns the replaced value and the [`into_inner`](Cell::into_inner) method consumes the
35-
//! `Cell<T>` and returns the interior value. Additionally, the [`set`](Cell::set) method
36-
//! replaces the interior value, dropping the replaced value.
40+
//! - All types have:
41+
//! - [`replace`](Cell::replace): replaces the current interior value and returns the replaced
42+
//! value.
43+
//! - [`into_inner`](Cell::into_inner): this method consumes the `Cell<T>` and returns the
44+
//! interior value.
45+
//! - [`set`](Cell::set): this method replaces the interior value, dropping the replaced value.
46+
//!
47+
//! `Cell<T>` is typically used for more simple types where copying or moving values isn't too
48+
//! resource intensive (e.g. numbers), and should usually be preferred over other cell types when
49+
//! possible. For larger and non-copy types, `RefCell` provides some advantages.
3750
//!
38-
//! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
51+
//! ## `RefCell<T>`
52+
//!
53+
//! [`RefCell<T>`] uses Rust's lifetimes to implement "dynamic borrowing", a process whereby one can
3954
//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
40-
//! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
41-
//! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
42-
//! to borrow a value that is already mutably borrowed; when this happens it results in thread
43-
//! panic.
55+
//! tracked at _runtime_, unlike Rust's native reference types which are entirely tracked
56+
//! statically, at compile time.
57+
//!
58+
//! An immutable reference to a `RefCell`'s inner value (`&T`) can be obtained with
59+
//! [`borrow`](`RefCell::borrow`), and a mutable borrow (`&mut T`) can be obtained with
60+
//! [`borrow_mut`](`RefCell::borrow_mut`). When these functions are called, they first verify that
61+
//! Rust's borrow rules will be satisfied: any number of immutable borrows are allowed or a
62+
//! single immutable borrow is allowed, but never both. If a borrow is attempted that would violate
63+
//! these rules, the thread will panic.
64+
//!
65+
//! The corresponding [`Sync`] version of `RefCell<T>` is [`RwLock<T>`].
66+
//!
67+
//! ## `OnceCell<T>`
68+
//!
69+
//! [`OnceCell<T>`] is somewhat of a hybrid of `Cell` and `RefCell` that works for values that
70+
//! typically only need to be set once. This means that a reference `&T` can be obtained without
71+
//! moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike
72+
//! `RefCell`). However, its value can also not be updated once set unless you have a mutable
73+
//! reference to the `OnceCell`.
74+
//!
75+
//! `OnceCell` provides the following methods:
76+
//!
77+
//! - [`get`](OnceCell::get): obtain a reference to the inner value
78+
//! - [`set`](OnceCell::set): set the inner value if it is unset (returns a `Result`)
79+
//! - [`get_or_init`](OnceCell::get_or_init): return the inner value, initializing it if needed
80+
//! - [`get_mut`](OnceCell::get_mut): provide a mutable reference to the inner value, only available
81+
//! if you have a mutable reference to the cell itself.
82+
//!
83+
//! The corresponding [`Sync`] version of `OnceCell<T>` is [`OnceLock<T>`].
84+
//!
4485
//!
4586
//! # When to choose interior mutability
4687
//!
@@ -188,6 +229,8 @@
188229
//! [`Rc<T>`]: ../../std/rc/struct.Rc.html
189230
//! [`RwLock<T>`]: ../../std/sync/struct.RwLock.html
190231
//! [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
232+
//! [`OnceLock<T>`]: ../../std/sync/struct.OnceLock.html
233+
//! [`Sync`]: ../../std/marker/trait.Sync.html
191234
//! [`atomic`]: crate::sync::atomic
192235
193236
#![stable(feature = "rust1", since = "1.0.0")]
@@ -419,7 +462,7 @@ impl<T> Cell<T> {
419462
mem::replace(unsafe { &mut *self.value.get() }, val)
420463
}
421464

422-
/// Unwraps the value.
465+
/// Unwraps the value, consuming the cell.
423466
///
424467
/// # Examples
425468
///
@@ -1969,7 +2012,7 @@ impl<T> UnsafeCell<T> {
19692012
UnsafeCell { value }
19702013
}
19712014

1972-
/// Unwraps the value.
2015+
/// Unwraps the value, consuming the cell.
19732016
///
19742017
/// # Examples
19752018
///
@@ -2133,7 +2176,7 @@ impl<T> SyncUnsafeCell<T> {
21332176
Self { value: UnsafeCell { value } }
21342177
}
21352178

2136-
/// Unwraps the value.
2179+
/// Unwraps the value, consuming the cell.
21372180
#[inline]
21382181
pub const fn into_inner(self) -> T {
21392182
self.value.into_inner()

library/core/src/cell/once.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ use crate::mem;
44

55
/// A cell which can be written to only once.
66
///
7-
/// Unlike [`RefCell`], a `OnceCell` only provides shared `&T` references to its value.
8-
/// Unlike [`Cell`], a `OnceCell` doesn't require copying or replacing the value to access it.
7+
/// This allows obtaining a shared `&T` reference to its inner value without copying or replacing
8+
/// it (unlike [`Cell`]), and without runtime borrow checks (unlike [`RefCell`]). However,
9+
/// only immutable references can be obtained unless one has a mutable reference to the cell
10+
/// itself.
911
///
1012
/// For a thread-safe version of this struct, see [`std::sync::OnceLock`].
1113
///

library/std/src/sync/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,9 @@
133133
//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
134134
//! most one thread at a time is able to access some data.
135135
//!
136-
//! - [`Once`]: Used for thread-safe, one-time initialization of a
136+
//! - [`Once`]: Used for a thread-safe, one-time global initialization routine
137+
//!
138+
//! - [`OnceLock`]: Used for thread-safe, one-time initialization of a
137139
//! global variable.
138140
//!
139141
//! - [`RwLock`]: Provides a mutual exclusion mechanism which allows
@@ -147,6 +149,7 @@
147149
//! [`mpsc`]: crate::sync::mpsc
148150
//! [`Mutex`]: crate::sync::Mutex
149151
//! [`Once`]: crate::sync::Once
152+
//! [`OnceLock`]: crate::sync::OnceLock
150153
//! [`RwLock`]: crate::sync::RwLock
151154
152155
#![stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)