diff --git a/src/bin/arcmutex.rs b/src/bin/arcmutex.rs new file mode 100644 index 0000000..4643176 --- /dev/null +++ b/src/bin/arcmutex.rs @@ -0,0 +1,26 @@ +use std::sync::{Arc, Mutex}; + +fn c(f: F) { + f(); +} + +fn main() { + let v = Arc::new(Mutex::new(vec![1, 2, 3])); + + c({ + let v = v.clone(); + move || { + println!("inner 1: {:?}", v); + v.lock().unwrap().push(4); + } + }); + c({ + let v = v.clone(); + move || { + println!("inner 2: {:?}", v); + v.lock().unwrap().push(5); + } + }); + + println!("outer: {:?}", v); +} diff --git a/src/bin/rcrefcell.rs b/src/bin/rcrefcell.rs new file mode 100644 index 0000000..34271d2 --- /dev/null +++ b/src/bin/rcrefcell.rs @@ -0,0 +1,30 @@ +use std::{cell::RefCell, rc::Rc}; + +fn c(f: F) { + f(); +} + +fn main() { + let v = Rc::new(RefCell::new(vec![1, 2, 3])); + + c({ + let v = v.clone(); + move || { + println!("inner 1: {:?}", v); + v.replace_with(|old| { + old.push(4); + old.to_vec() + }); + } + }); + c({ + let v = v.clone(); + move || { + println!("inner 2: {:?}", v); + // This seems more readable than the example from https://www.youtube.com/watch?v=FTsaDmf0f_0 shown above + v.borrow_mut().push(5); + } + }); + + println!("outer: {:?}", v); +}