about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorCorey Farwell <coreyf@rwell.org>2017-08-02 01:22:27 +0000
committerGitHub <noreply@github.com>2017-08-02 01:22:27 +0000
commit2d9893fda704b475165051419773d67256434a30 (patch)
treefe757a5e8798f37448f02c73bc2a502f63b2e390 /src/libcore
parentab3fb956f3b9b2cd5d444ec30dd58bdf25dea7c9 (diff)
parentd429a4eac81aea6070655cdfb5604187d94355a2 (diff)
downloadrust-2d9893fda704b475165051419773d67256434a30.tar.gz
rust-2d9893fda704b475165051419773d67256434a30.zip
Rollup merge of #43423 - xliiv:cell-example, r=steveklabnik
Add simple docs example for struct Cell
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/cell.rs28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs
index 35744f3f16b..21b5557db99 100644
--- a/src/libcore/cell.rs
+++ b/src/libcore/cell.rs
@@ -188,6 +188,34 @@ use ptr;
 
 /// A mutable memory location.
 ///
+/// # Examples
+///
+/// Here you can see how using `Cell<T>` allows to use mutable field inside
+/// immutable struct (which is also called '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, because my_struct is immutable
+/// // my_struct.regular_field = new_value;
+///
+/// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
+/// my_struct.special_field.set(new_value);
+/// assert_eq!(my_struct.special_field.get(), new_value);
+/// ```
+///
 /// See the [module-level documentation](index.html) for more.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Cell<T> {