O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Practical uses of interior mutability

The examples of Cell and RefCell were simplified, and you would most probably not 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 mentioned before, bindings are not fine-grained: a value is either immutable or mutable, and that includes all its fields if it's a struct or an enum. Cell and RefCell can turn an immutable thing into 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:

// interior-mutability.rs use std::cell::Cell; struct Point {     x: u8,  y: u8,  ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required