January 2019
Beginner to intermediate
554 pages
13h 31m
English
If you need Cell-like features for non-Copy types, there is the RefCell type. It uses a read/write pattern similar to how borrowing works, but moves the checks to runtime, which is convenient but not zero-cost. RefCell hands out references to the value, instead of returning things by value as is the case with the Cell type. Here's a sample program that
// refcell_basics.rs use std::cell::RefCell; #[derive(Debug)]struct Bag { item: Box<u32>} fn main() { let bag = RefCell::new(Bag { item: Box::new(1) }); let hand1 = &bag; let hand2 = &bag; *hand1.borrow_mut() = Bag { item: Box::new(2)}; *hand2.borrow_mut() = Bag { item: Box::new(3)}; let borrowed = hand1.borrow(); println!("{:?}", borrowed);}
As you can see, we can borrow
Read now
Unlock full access