Share one mutable counter between several owners with Rc<RefCell<i32>>
Several Clicker handles count clicks into one shared total. Write clickers, which returns n handles that all point at the same counter, and click, which adds one to it. Then explain why the field is Rc<RefCell<i32>> and not just Rc<i32> or RefCell<i32>.
Requirements:
- Keep every signature:
clicktakes&self,clickerstakes&Rc<RefCell<i32>>. - No
unsafe, noCell, nostatic; do not copy the number into each handle. mainstays as it is and prints4 3(the total, then the strong count).
use std::cell::RefCell;
use std::rc::Rc;
struct Clicker {
total: Rc<RefCell<i32>>,
}
impl Clicker {
fn click(&self) {
// your code here
}
}
fn clickers(total: &Rc<RefCell<i32>>, n: usize) -> Vec<Clicker> {
// your code here
}
fn main() {
let total = Rc::new(RefCell::new(0));
let list = clickers(&total, 2);
for c in &list {
c.click();
}
list[0].click();
list[0].click();
println!("{} {}", total.borrow(), Rc::strong_count(&total));
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
clickers gives each handle Rc::clone(total), so all share one RefCell and the count is 3; click runs *self.total.borrow_mut() += 1 through &self. Rc alone is read-only (E0594); RefCell alone has one owner.
- Writing
*self.total += 1on anRc<i32>, which fails with E0594 because anRchands out only shared access - Cloning the inner
RefCellinstead of theRc, so each handle counts on its own copy - Holding a
borrow()of the total while callingclick, which panics withRefCell already borrowed
- What does
Rc::strong_count(&total)report afterlistis dropped, and why? - What would you change to share this counter between threads?
Each handle gets its own Rc, but all of them point at one RefCell, and the RefCell allows changing the number through a shared reference:
use std::cell::RefCell;
use std::rc::Rc;
struct Clicker {
total: Rc<RefCell<i32>>,
}
impl Clicker {
fn click(&self) {
*self.total.borrow_mut() += 1;
}
}
fn clickers(total: &Rc<RefCell<i32>>, n: usize) -> Vec<Clicker> {
(0..n)
.map(|_| Clicker {
total: Rc::clone(total),
})
.collect()
}
fn main() {
let total = Rc::new(RefCell::new(0));
let list = clickers(&total, 2);
for c in &list {
c.click();
}
list[0].click();
list[0].click();
println!("{} {}", total.borrow(), Rc::strong_count(&total)); // 4 3
}Rc::clone does not copy the number; it adds an owner, so total and the two handles give a strong count of 3. The guard from borrow_mut() lives until the end of the statement, so each increment is a short borrow and the clicks never collide.
Both wrappers are needed. With an Rc<i32> field, *self.total += 1 does not compile: error[E0594]: cannot assign to data in an `Rc` — an Rc hands out only &i32, or two owners could get a &mut at once. With a RefCell<i32> field the number can change, but a RefCell has one owner: clone() would make an independent copy, and each handle would count on its own. Rc gives many owners, RefCell gives mutation through &self checked at run time. Across threads the same pair is Arc<Mutex<i32>>, and a single number needs only Arc<AtomicI32>.