Interior mutability

As we saw previously, Rust protects us at compile time from the pointer aliasing problem by allowing only a single mutable reference at any given scope. However, there are cases where it becomes too restrictive, making code that we know is safe not pass the compiler because of the strict borrow checking. For these situations, one of the solutions is to move the borrow checking from compile time to runtime, which is achieved with interior mutability. Before we talk about the types that enable interior mutability, we need to understand the concept of interior mutability and inherited mutability:

  • Inherited mutability: This is the default mutability you get when you take a &mut reference to some struct. This also implies that you can modify any of the fields of the struct.
  • Interior mutability: In this kind of mutability, even if you have a &SomeStruct reference to some type, you can modify its fields if the fields have the type as  Cell<T> or RefCell<T>.

Interior mutability allows for bending the borrowing rules a bit, but it also puts the burden on the programmer to ensure that no two mutable borrows are present at runtime. These types offload the detection of multiple mutable references from compile time to runtime and undergo a panic if two mutable references to a value exist. Interior mutability is often used when you want to expose an immutable API to users, despite having mutable parts to the API internally. The standard library has two generic smart pointer types that provide shared mutability: Cell and RefCell.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset