Summary - Interior mutability
- Rust course
- Intermediate
- Lesson 41/115
- 5 min
Build a graph edge list with Rc<RefCell<T>>.
Interior mutability summary
Interior mutability makes it safe to change data behind a &T. Cell<T>: get/set for Copy values, no panics. RefCell<T>: runtime-checked borrow/borrow_mut, panic on violation. Rc<RefCell<T>>: shared and mutable data. Weak: a non-owning link that prevents cycles. Their counterparts across threads are Mutex, RwLock and the atomic types.
A shared account
Two owners change the same balance; there is also a weak link that doesn't keep the value alive:
let hesap = Rc::new(RefCell::new(100));
let kopya = Rc::clone(&hesap);
*kopya.borrow_mut() -= 30;
let zayif = Rc::downgrade(&hesap);
println!("{} {} {}",
hesap.borrow(),
Rc::strong_count(&hesap),
Rc::weak_count(&hesap)); // 70 2 1Practice Shared balance
Write the example above: Rc::new(RefCell::new(100)), subtract 30 through a copy, take a weak link with Rc::downgrade. Print the balance, strong_count and weak_count separated by spaces.
Starter code
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
// buraya yaz
}Sample solution
use std::cell::RefCell;
use std::rc::Rc;
fn main() {
let hesap = Rc::new(RefCell::new(100));
let kopya = Rc::clone(&hesap);
*kopya.borrow_mut() -= 30;
let _zayif = Rc::downgrade(&hesap);
println!("{} {} {}", hesap.borrow(), Rc::strong_count(&hesap), Rc::weak_count(&hesap));
}Expected output
70 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>Rc::weak_count</code> count?
- Weak pointers created with Rc::downgrade Correct answer
- All owners
- Dropped copies
- Borrows
Explanation: Weak pointers don't keep the value alive; it is dropped only when strong_count reaches zero.
2 Weak link
let zayif = Rc::____(&hesap);
let zayif = Rc::downgrade(&hesap);
Explanation: Rc::downgrade produces a non-owning Weak pointer.
3 Group summary
| Term | Meaning |
|---|---|
Cell<T> |
Copy value, no panic |
RefCell<T> |
Runtime borrows |
Rc<RefCell<T>> |
Shared and mutable |
Weak<T> |
Prevents cycles |