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 {
16 Callbacks { callbacks: Vec::new() }
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 {
72 CallbacksMut { callbacks: Vec::new() }
75 pub fn register<F: FnMut(i32)+'static>(&mut self, callback: F) {
79 pub fn call(&mut self, val: i32) {
80 for callback in self.callbacks.iter() {
81 // We have to *explicitly* borrow the contents of a `RefCell` by calling `borrow` or `borrow_mut`.
82 let mut closure = callback.borrow_mut();
83 // Unfortunately, Rust's auto-dereference of pointers is not clever enough here. We thus have to explicitly
84 // dereference the smart pointer and obtain a mutable borrow of the content.
90 // Now we can repeat the demo from the previous part - but this time, our `CallbacksMut` type
92 fn demo_mut(c: &mut CallbacksMut) {
93 c.register(|val| println!("Callback 1: {}", val));
97 let mut count: usize = 0;
98 c.register(move |val| {
100 println!("Callback 2: {} ({}. time)", val, count);
103 c.call(1); c.clone().call(2);
106 // **Exercise 12.1**: Write some piece of code using only the available, public interface of `CallbacksMut` such that a reentrant call to a closure
107 // is happening, and the program aborts because the `RefCell` refuses to hand out a second mutable borrow of the closure's environment.