- // If we change the two "borrow" below to "borrow_mut", you can get a panic even with a "call" that requires a
- // mutable borrow. However, that panic is then triggered by our own, external `RefCell` (so it's kind of our fault),
- // rather than being triggered by the `RefCell` in the `Callbacks`.
- {
- let c2 = c.clone();
- c.borrow_mut().register(move |val| c2.borrow().call(val+val) );
- }
+ // This adds the cyclic closure, which refers to the `Callbacks` though `c2`.
+ let c2 = c.clone();
+ c.borrow_mut().register(move |val| {
+ // This `borrow_mut` won't fail because we are careful below to close the `RefCell`
+ // before triggering the cycle. You can see that this is the case because the log message
+ // below is printed.
+ let mut guard = c2.borrow_mut();
+ println!("Callback called with {}, ready to go for nested call.", val);
+ guard.call(val+val)
+ } );