January 2019
Beginner to intermediate
554 pages
13h 31m
English
Consider this program, where we have a requirement to mutate bag with two mutable references to it:
// without_cell.rs use std::cell::Cell; #[derive(Debug)]struct Bag { item: Box<u32>} fn main() { let mut bag = Cell::new(Bag { item: Box::new(1) }); let hand1 = &mut bag; let hand2 = &mut bag; *hand1 = Cell::new(Bag {item: Box::new(2)}); *hand2 = Cell::new(Bag {item: Box::new(2)});}
But, of course, this does not compile due to the borrow checking rules:

We can make this work by encapsulating the bag value inside a Cell. Our code is updated as follows:
// cell.rs use std::cell::Cell; #[derive(Debug)]struct Bag { item: Box<u32>} Read now
Unlock full access