File tree 1 file changed +28
-0
lines changed
1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -188,6 +188,34 @@ use ptr;
188
188
189
189
/// A mutable memory location.
190
190
///
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
+ ///
191
219
/// See the [module-level documentation](index.html) for more.
192
220
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
193
221
pub struct Cell < T > {
You can’t perform that action at this time.
0 commit comments