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

Interior mutability for Copy types - Cell<T>

As seen before, Rust protects us at compile time from the aliasing problem by allowing only a single mutable reference at the same time. However, there are cases where that is too restrictive, making code that we know is safe not pass the compiler because of the strict borrow checks.

Interior mutability allows us to bend the borrowing rules a bit. The standard library has two generic types for this: Cell and RefCell. Cell is zero-cost: the compiler generates code that is similar to primitive mutable references. The point is that, as we saw before, multiple mutable references are not acceptable. Cell<T> requires that the enclosed types implement the Copy trait.

Because Cell bends the rules, you ...

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