Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

armanriazi•rust•pattern•design•interior•mutability•refcell

Interior mutability is a design pattern in Rust that allows you to mutate data even when there are immutable references to that data; normally, this action is disallowed by the borrowing rules. To mutate data, the pattern uses unsafe code inside a data structure to bend Rust’s usual rules that govern mutation and borrowing. 
RefCell<T> type that follows the interior mutability pattern.
Unlike Rc<T>, the RefCell<T> type represents single ownership over the data it holds. So, what makes RefCell<T> different from a type like Box<T>? Recall the borrowing rules you learned in Chapter 4:
Similar to Rc<T>, RefCell<T> is only for use in single-threaded scenarios and will give you a compile-time error if you try using it in a multithreaded context.
At any given time, you can have either (but not both of) one mutable reference or any number of immutable references.
References must always be valid.
{
RefCell<T> uses Rust’s lifetimes to implement ‘dynamic borrowing’, a process whereby one can claim temporary, exclusive, mutable access to the inner value.
Because RefCell<T> borrows are dynamic it is possible to attempt to borrow a value that is already mutably borrowed; when this happens it results in thread panic.
} 
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
7+2 =