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 move types - RefCell<T>

If you need Cell-like features for your non-copying types, RefCell can help. It uses read/write locks at runtime for you, which is convenient but not zero-cost. The other difference is that whereas Cell lets you handle actual values, RefCell handles references. This means that the same mutable borrow restrictions are in effect that work with the primitive let reference bindings, but RefCell restrictions are checked at runtime instead of compile-time.

This is what happens if you try to use a Cell<T> with a type that moves instead of copies. In other words, with a type that does not implement the Copy trait:

// multiple-move-types.rs use std::cell::Cell; struct Foo {     number: u8 } fn main() { ...

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