Interior Mutability
Mutability Pattern where an immutable type reveals an API for changing an interior value, and the borrowing regulations. The Interior Mutability marking involves using unprotected code within a data structure to bend Rust’s normal rules through mutation and borrowing. When the compiler cannot guarantee that the borrowing rules will be followed at runtime, the interior mutability pattern is used. After that, the unsafe code is covered up by a secure API, and the outer type remains unchangeable.
We can have a List that is immutable on the outside by using RefCell<T>, but we can use the methods on RefCell<T> to get access to its internal mutability so we can change our data whenever we need to. We’ve decided to give up some speed in exchange for more flexibility in our data structures because RefCell<T> does prevent data races.
Let’s look at a scenario in which we can make use of RefCell<T> to alter an immutable value. For example, When you have a value that cannot be changed, you can’t borrow it in any way because of the borrowing rules.
Example 1:
Rust
fn main() { let r = 4; let p = & mut r; } |
Output :
The request failed with status code 400. We have seen that the immutable value cannot be borrowed in a mutable way in the above example. However, the only method for achieving interior mutability is RefCell.
Example 2:
Rust
use std::cell::RefCell; fn main() { let r = RefCell::new(4); let s = r.borrow(); let q = r.borrow(); println!( "Now value of s is : {}" ,s); println!( "Now value of q is : {}" ,q); } |
Output :
There are more types in the standard library that offer interior mutability besides RefCell<T>. (Cell<T> is similar but instead of giving references to the inner value like RefCell<T> does, the value is copied in and out of the Cell<T>. Mutex<T> offers interior mutability that is safe to use across threads.
Rust – RefCell(T) and interior Mutability
.Rust is a memory-safe compiled programming language that delivers high-level simplicity with low-level performance. It’s a popular choice for building systems where performance is absolutely critical like Game engine databases or Operating systems and is an excellent choice when targeting web assembly, it started as a side project of the grid on four in 2007.
It was sponsored by Mozilla in 2009 and has been ranked the most loved programming language every year since 2016<T>
Let’s explore the RefCell<T> type that follows the interior Mutability marking, Where, Rust’s interior mutability is a map marking that lets you change data even when references to it cannot be changed; (In most cases, the borrowing regulations do not permit this kind of behavior. )