Interior Mutability Concepts
RefCell
Borrow Rules at Runtime
RefCell<T> checks Rust's borrow rules while the program runs, allowing mutation through a shared owner when the borrowing pattern is valid.
Program
Play the program to choose a log item and push it into a vector stored inside RefCell.
refcell_buffer.rs
use std::cell::RefCell;
fn main() {
let item = ;
let log = RefCell::new(Vec::new());
log.borrow_mut().push("start");
log.borrow_mut().push(item);
let count = log.borrow().len();
println!("{count}");
}
use std::cell::RefCell;
fn main() {
let item = ;
let log = RefCell::new(Vec::new());
log.borrow_mut().push("start");
log.borrow_mut().push(item);
let count = log.borrow().len();
println!("{count}");
}
use std::cell::RefCell;
fn main() {
let item = ;
let log = RefCell::new(Vec::new());
log.borrow_mut().push("start");
log.borrow_mut().push(item);
let count = log.borrow().len();
println!("{count}");
}
RefCell<T>
`RefCell<T>` moves borrow checking for the wrapped value to runtime.
borrow_mut
`borrow_mut` grants a temporary mutable borrow when no conflicting borrow exists.
borrow
`borrow` grants a temporary shared borrow for reading.