1 // Rust-101, Part 12: Rc, Interior Mutability, Cell, RefCell
2 // =========================================================
5 use std::cell::{Cell, RefCell};
11 callbacks: Vec<Rc<Fn(i32)>>,
15 pub fn new() -> Self {
19 // Registration works just like last time, except that we are creating an `Rc` now.
20 pub fn register<F: Fn(i32)+'static>(&mut self, callback: F) {
24 pub fn call(&self, val: i32) {
25 // We only need a shared iterator here. Since `Rc` is a smart pointer, we can directly call the callback.
26 for callback in self.callbacks.iter() {
33 fn demo(c: &mut Callbacks) {
34 c.register(|val| println!("Callback 1: {}", val));
35 c.call(0); c.clone().call(1);
39 let mut c = Callbacks::new();
43 // ## Interior Mutability
45 // So, let us put our counter in a `Cell`, and replicate the example from the previous part.
46 fn demo_cell(c: &mut Callbacks) {
48 let count = Cell::new(0);
49 // Again, we have to move ownership if the `count` into the environment closure.
50 c.register(move |val| {
51 // In here, all we have is a shared borrow of our environment. But that's good enough for the `get` and `set` of the cell!
52 let new_count = count.get()+1;
54 println!("Callback 2: {} ({}. time)", val, new_count);
58 c.call(2); c.clone().call(3);
64 // Our final version of `Callbacks` puts the closure environment into a `RefCell`.
67 callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
71 pub fn new() -> Self {
75 pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
76 let cell = Rc::new(RefCell::new(callback));
80 pub fn call(&mut self, val: i32) {
81 for callback in self.callbacks.iter() {
82 // We have to *explicitly* borrow the contents of a `RefCell` by calling `borrow` or `borrow_mut`.
83 let mut closure = callback.borrow_mut();
84 // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
85 // dereference the smart pointer and obtain a mutable borrow of the content.
91 // Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
93 fn demo_mut(c: &mut CallbacksMut) {
94 c.register(|val| println!("Callback 1: {}", val));
98 let mut count: usize = 0;
99 c.register(move |val| {
101 println!("Callback 2: {} ({}. time)", val, count);
104 c.call(1); c.clone().call(2);
107 // **Exercise 12.1**: Change the type of `call` to ask only for a shared borrow. Then write some piece of code using only the available, public
108 // interface of `CallbacksMut` such that a reentrant call to `call` is happening, and the program aborts because the `RefCell` refuses to hand
109 // out a second mutable borrow to its content.