Skip to content

Commit 2d9893f

Browse files
authored
Rollup merge of #43423 - xliiv:cell-example, r=steveklabnik
Add simple docs example for struct Cell
2 parents ab3fb95 + d429a4e commit 2d9893f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libcore/cell.rs

+28
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,34 @@ use ptr;
188188

189189
/// A mutable memory location.
190190
///
191+
/// # Examples
192+
///
193+
/// Here you can see how using `Cell<T>` allows to use mutable field inside
194+
/// immutable struct (which is also called 'interior mutability').
195+
///
196+
/// ```
197+
/// use std::cell::Cell;
198+
///
199+
/// struct SomeStruct {
200+
/// regular_field: u8,
201+
/// special_field: Cell<u8>,
202+
/// }
203+
///
204+
/// let my_struct = SomeStruct {
205+
/// regular_field: 0,
206+
/// special_field: Cell::new(1),
207+
/// };
208+
///
209+
/// let new_value = 100;
210+
///
211+
/// // ERROR, because my_struct is immutable
212+
/// // my_struct.regular_field = new_value;
213+
///
214+
/// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
215+
/// my_struct.special_field.set(new_value);
216+
/// assert_eq!(my_struct.special_field.get(), new_value);
217+
/// ```
218+
///
191219
/// See the [module-level documentation](index.html) for more.
192220
#[stable(feature = "rust1", since = "1.0.0")]
193221
pub struct Cell<T> {

0 commit comments

Comments
 (0)