[][src]Module show_notes::e016

RefCells and code smells

Notes

What are the Cell and RefCell types, and when should we use them?

Today, we follow up both the detailed discussion of smart pointers in e015 and the closely related discussion in Interview 2 with Raph Levien, and look at two types you need to have a good idea how to deal with if you want to use these smart pointer types more ergonomically---that is, how to use them without feeling like you're beating your head against a wall!

The descriptions of the code below are minimal; see the inline comments in the source for the actual informative discussion.

A comment on the code samples

Note that in several cases below we use &[] to borrow a reference to a slice, rather than requiring this to pass a reference to a Vec specifically. Making the first argument be of type &Vec<RefCell<SimpleNonCopyable>> would also work, but would be more restrictive in what it could and couldn't accept. Since Vec implements Deref to automatically convert to slices, this works just fine, and is more general. This is how you should usually write function signatures which operate on reference to vectors (and likewise for other types which can dereference to slices). We'll talk about this more in a future episode!

Sponsors

(Thanks to the couple people donating who opted out of the reward tier, as well. You know who you are!)

Become a sponsor

Contact

Structs

SimpleContainer

A container showing a type where Cell<T> works with Vec<T>.

SimpleNonCopyable

A container showing where Cell<T> doesn't work and RefCell<T> does.

Functions

add_to_each_string

Demonstrate interior mutability with Rc and RefCell.

demonstrate_need_for_cell

Demonstrate how you need Cell<T> even just with a Vec<T>;

double_cell

Operate mutably on the contenets of an immutable reference to a Vec.