usagi / rust-memory-container-cs

Rust Memory Container Cheat-sheet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cell does not require Copy types

juhdanad opened this issue · comments

The infographic suggests that Cell can only be used with Copy types. But you can move anything into a Cell. See the replace method.

Hmm, yes, you are right. I'll add a note or modify the related cheat in the next "rev.2". Thank you for your suggestion.

// eg.
let cell = Cell::new(vec![1,2,3]);
let original = cell.replace(vec![4,5,6]);
assert_eq!( &original[..], [1,2,3] ); // ok

According to the documentation of the std::cell crate,

Cell types come in two flavors: Cell<T> and RefCell<T>. Cell<T> implements interior mutability by moving values in and out of the Cell<T>. To use references instead of values, one must use the RefCell<T> type, acquiring a write lock before mutating.

So I think the choice of Cell vs RefCell depends on whether you want plain & references to the contained data or not.

Note: I'll plan to merge rev-2-preparing branch to master in the next weekend.