advancedSmart Pointers
Cell and RefCell
Interior mutability with Cell and RefCell.
Cell and RefCell
Interior mutability with Cell and RefCell.
Difficulty
Advanced
Code
rust
use std::cell::RefCell;
fn main() {
let data = RefCell::new(vec![1, 2, 3]);
// borrow mutably
data.borrow_mut().push(4);
println!("{:?}", data.borrow());
// borrow immutably multiple times is fine
let r1 = data.borrow();
let r2 = data.borrow();
println!("{:?} {:?}", r1, r2);
}Explanation
This example demonstrates how to use cell and refcell in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the smart-pointers category to build a complete understanding of this topic.