January 2019
Beginner to intermediate
554 pages
13h 31m
English
In the previous section, the examples on using Cell and RefCell were simplified, and you most probably won't need to use them in that form in real code. Let's take a look at some actual benefits that these types would give us.
As we mentioned previously, the mutability of a binding is not fine-grained; a value is either immutable or mutable, and that includes all of its fields if it's a struct or an enum. Cell and RefCell can turn an immutable thing into something that's mutable, allowing us to define parts of an immutable struct as mutable.
The following piece of code augments a struct with two integers and a sum method to cache the answer of the sum and return the cached value if it exists:
// cell_cache.rs
Read now
Unlock full access