RefCell<T>Interior mutability pattern is a pattern is used to mutate the reference if we have an immutable reference. RefCell<T> can be used to achieve the interior mutability. Important Points to remember:
Interior MutabilityAccording to the borrowing rules, if we have an immutable value, then we cannot borrow mutably. Let's see a simple example: Output: In the above example, we have seen that the immutable value cannot be borrowed mutably. But, RefCell is the one way to achieve the interior mutability. Keeping Track of Borrows at Runtime with RefCell<T>RefCell<T> consists of two methods that keep track of borrows at runtime:
Note: Both the types Ref<T> and RefMut<T> implements Deref trait. Therefore, they can be treated as regular references.Some Important Points:
borrow() methodThe borrow() method borrows the immutable value. Multiple immutable borrows can be taken at the same time. Syntax: Let's see a simple example when multiple immutable borrow occurs: Output: Let's see a simple example of panic condition: Output: In the above example, program panics at runtime as immutable borrows and mutable borrows cannot occur at the same time. borrow_mut() methodThe borrow_mut() method borrows the mutable value. Mutable borrows can occur once. Syntax: Let's see a simple example: Let's see a simple example of panic condition: Output: In the above example, mutable borrow occurs twice. Therefore, the program panics at the runtime and throws an error 'already borrowed: BorrowMutError'. Multiple owners of Mutable Data By combining Rc<T> and RefCell<T>We can combine Rc<T> and RefCell<T> so that we can have multiple owners of mutable data. The Rc<T> lets you have multiple owners of a data, but it provides only immutable access to the data. The RefCell<T> lets you to mutate the data. Therefore, we can say that the combination of Rc<T> and RefCell<T> provides the flexibility of having multiple owners with mutable data. Let's see a simple example: Output: In the above example, we create a variable 'val' and store the value "java" to the variable 'val'. Then, we create the list 'a' and we clone the 'val' variable so that both the variable 'a' and 'val' have the ownership of 'java' value rather than transferring the ownership from 'val' to 'a' variable. After creating 'a' list, we create 'b' and 'c' list and clones the 'a' list. After creating the lists, we replace the value of 'val' variable with "C#" language" by using the borrow_mut() method. Next Topic# |