finish part 14
[rust-101.git] / src / part15.rs
1 // Rust-101, Part 15: Interior Mutability (cont.), RefCell, Cell, Drop
2 // ===================================================================
3
4 //@ [`RefCell`](http://doc.rust-lang.org/beta/std/cell/struct.RefCell.html)
5 //@ [`is very much like `RwLock`, but it's not thread-safe: "Locking" is done without atomic operations.
6 //@ One can also see it as a dynamically checked version of Rust's usual borrowing rules. You have to explicitly say
7 //@ when you want to borrow the data in there shared, or mutably, and Rust will complain at run-time if you have
8 //@ a mutable borrow while any other borrow is active. You can then write programs that Rust may otherwise not
9 //@ accept. Sending a shared borrow to this to another thread is dangerous, as the checks are not performed in
10 //@ a thread-safe manner. However, sending the *entire* `RefCell` is okay, because there's only ever one owner, and all
11 //@ we need to ensure is that everybody attempting to borrow is in the same thread as the owner. <br/>
12 //@ [`Cell<T>`](http://doc.rust-lang.org/beta/std/cell/struct.Cell.html) is like a stripped-down version of `RefCell<T>`: It doesn't allow
13 //@ you to borrow its content. Instead, it has a methods `get` and `set` to change the value stored in the cell, and to copy it out.
14 //@ For obvious reasons, this requires `T` to be `Copy`.
15 //@ 
16 //@ You can also think about all these types coming from the other end: Starting with `Cell`, we have a primitive for
17 //@ interior mutability that provides `get` and `set`, both just requiring a shared borrow. Think of these functions as
18 //@ mutating the *content* of the cell, but not the cell itself, the container. (Just like in ML, where assignment to a 
19 //@ `ref` changes the content, not the location.) However, due to the ownership discipline, `Cell` only works for types
20 //@ that are `Copy`. Hence we also have `RefCell`, which allows working with the data right in the cell, rather than
21 //@ having to copy it out. `RefCell` uses non-atomic operations for this purpose, so for the multi-threaded setting, there's
22 //@ the thread-safe `RwLock`. And finally, in case a distinction between readers and writers is not helpful, one can use the
23 //@ more efficient `Mutex`.
24
25 //@ [index](main.html) | [previous](part14.html) | [next](main.html)