Open In App

Rust – RefCell(T) and interior Mutability

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

.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. ) 

RefCell<T>:

  • RefCell<T>, which is not a smart pointer in and of itself, but controls access to “smart pointers like Ref and RefMut to implement borrowing rules at runtime rather than at compile time”.                                                                                                                                                                               
  • RefCell<T> represents the single title with reference counting.                                                                                                                                
  • RefCell<T> employs reference counting to monitor the number of active burrows while the program is running.                                                               
  • RefCell<T> is mostly used in a unique-threaded schema, but in a multithreaded schema, it won’t be accurate.                                            
  • Also, the reference counting in RefCell<T> is not thread-safe, so it’s not possible to share RefCell<T> data between threads. 

Important Points to remember:

  1. The marking breaks the normal rules of mutation and borrowing that Rust follows in order to alter data by employing unencrypted code within a data structure. 
  2. Classes with the inner mutability manifestation can still be utilized even if the compiler cannot ensure that the borrowing regulations will be discovered at runtime. 
  3. After that, the involved unencrypted code is encased in a protected API, and the outermost type can still be changed. 
  4. RefCell<T> is useful when you know that the borrowing rules are respected, but the compiler can’t understand  that’s true.                                                                                                                                        

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.                                              



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads