RefCell lets you change data even when Rust normally would not allow it. It helps manage data safely inside a single thread.
0
0
RefCell overview in Rust
Introduction
When you want to change data inside something that is usually read-only.
When you need to borrow data mutably but only at runtime.
When you want to check borrowing rules while the program runs, not at compile time.
When you have shared data but only one part changes it at a time.
When you want to avoid complex ownership rules but still keep safety.
Syntax
Rust
use std::cell::RefCell; let data = RefCell::new(5); // Borrow immutably let value = data.borrow(); // Borrow mutably let mut value_mut = data.borrow_mut();
RefCell::new(value) creates a new RefCell holding the value.
borrow() gives an immutable reference, borrow_mut() gives a mutable reference.
Examples
This example shows how to read the value inside a RefCell.
Rust
use std::cell::RefCell; let data = RefCell::new(10); let val = data.borrow(); println!("Value: {}", *val);
This example shows how to change the value inside a RefCell.
Rust
use std::cell::RefCell; let data = RefCell::new(10); { let mut val_mut = data.borrow_mut(); *val_mut += 5; } println!("Updated value: {}", *data.borrow());
You can also use RefCell with complex data like vectors to modify them.
Rust
use std::cell::RefCell; let data = RefCell::new(vec![1, 2, 3]); data.borrow_mut().push(4); println!("Vector: {:?}", *data.borrow());
Sample Program
This program shows how RefCell allows changing a value safely inside one thread. It borrows the value immutably, then mutably changes it, then reads it again.
Rust
use std::cell::RefCell;
fn main() {
let shared_number = RefCell::new(100);
// Borrow immutably
let num1 = shared_number.borrow();
println!("First borrow: {}", *num1);
// Borrow mutably
{
let mut num2 = shared_number.borrow_mut();
*num2 += 50;
println!("After mutation: {}", *num2);
}
// Borrow immutably again
let num3 = shared_number.borrow();
println!("Final value: {}", *num3);
}OutputSuccess
Important Notes
RefCell checks borrowing rules at runtime, so borrowing errors cause the program to panic.
Use RefCell only when you are sure you need interior mutability inside one thread.
For multi-threaded cases, use types like Mutex or RwLock.
Summary
RefCell allows changing data even when Rust normally forbids it.
It enforces borrowing rules at runtime, not compile time.
Use it for safe interior mutability inside a single thread.