pub struct Cell<T: ?Sized> { /* private fields */ }
Expand description
A mutable memory location.
§Memory layout
Cell<T>
has the same memory layout and caveats as
UnsafeCell<T>
. In particular, this means that
Cell<T>
has the same in-memory representation as its inner type T
.
§Examples
In this example, you can see that Cell<T>
enables mutation inside an
immutable struct. In other words, it enables “interior mutability”.
use std::cell::Cell;
struct SomeStruct {
regular_field: u8,
special_field: Cell<u8>,
}
let my_struct = SomeStruct {
regular_field: 0,
special_field: Cell::new(1),
};
let new_value = 100;
// ERROR: `my_struct` is immutable
// my_struct.regular_field = new_value;
// WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
// which can always be mutated
my_struct.special_field.set(new_value);
assert_eq!(my_struct.special_field.get(), new_value);
See the module-level documentation for more.
Implementations§
source§impl<T> Cell<T>
impl<T> Cell<T>
1.17.0 · sourcepub fn swap(&self, other: &Self)
pub fn swap(&self, other: &Self)
Swaps the values of two Cell
s.
The difference with std::mem::swap
is that this function doesn’t
require a &mut
reference.
§Panics
This function will panic if self
and other
are different Cell
s that partially overlap.
(Using just standard library methods, it is impossible to create such partially overlapping Cell
s.
However, unsafe code is allowed to e.g. create two &Cell<[i32; 2]>
that partially overlap.)
§Examples
1.17.0 · sourcepub fn replace(&self, val: T) -> T
pub fn replace(&self, val: T) -> T
Replaces the contained value with val
, and returns the old contained value.
§Examples
1.17.0 (const: unstable) · sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Unwraps the value, consuming the cell.
§Examples
source§impl<T: Copy> Cell<T>
impl<T: Copy> Cell<T>
source§impl<T: ?Sized> Cell<T>
impl<T: ?Sized> Cell<T>
1.12.0 (const: 1.32.0) · sourcepub const fn as_ptr(&self) -> *mut T
pub const fn as_ptr(&self) -> *mut T
Returns a raw pointer to the underlying data in this cell.
§Examples
1.11.0 · sourcepub fn get_mut(&mut self) -> &mut T
pub fn get_mut(&mut self) -> &mut T
Returns a mutable reference to the underlying data.
This call borrows Cell
mutably (at compile-time) which guarantees
that we possess the only reference.
However be cautious: this method expects self
to be mutable, which is
generally not the case when using a Cell
. If you require interior
mutability by reference, consider using RefCell
which provides
run-time checked mutable borrows through its borrow_mut
method.
§Examples
source§impl<T> Cell<[T]>
impl<T> Cell<[T]>
1.37.0 · sourcepub fn as_slice_of_cells(&self) -> &[Cell<T>]
pub fn as_slice_of_cells(&self) -> &[Cell<T>]
Returns a &[Cell<T>]
from a &Cell<[T]>