Created
September 20, 2019 21:22
-
-
Save rust-play/e6a308f5c4e669054d33dc09e2013224 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::ops::*; | |
fn main() { | |
let mut times_vec_updated = 0; | |
let mut vec = OnUpdate(vec![], |v| { | |
eprintln!("Vec updated: {:?}", v); | |
times_vec_updated += 1; | |
}); | |
vec.borrow_mut().push(5); | |
vec.borrow_mut().push(6); | |
vec.borrow_mut().push(7); | |
dbg!(times_vec_updated); | |
let mut int = OnUpdate(10, |v| { | |
eprintln!("Int updated: {:?}", v); | |
}); | |
*int.borrow_mut() += 5; | |
} | |
#[derive(Debug, Clone, Copy)] | |
struct OnUpdate<T, F: FnMut(&T) -> ()>(T, F); | |
impl<T, F: FnMut(&T) -> ()> OnUpdate<T, F> { | |
fn borrow_mut(&mut self) -> MutBorrow<T, F> { | |
MutBorrow(&mut self.0, &mut self.1) | |
} | |
} | |
#[derive(Debug)] | |
struct MutBorrow<'a, T, F: FnMut(&T) -> ()>(&'a mut T, &'a mut F); | |
impl<'a, T, F: FnMut(&T) -> ()> Drop for MutBorrow<'a, T, F> { | |
fn drop(&mut self) { | |
(self.1)(&self.0) | |
} | |
} | |
impl<'a, T, F: FnMut(&T) -> ()> Deref for MutBorrow<'a, T, F> { | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
&self.0 | |
} | |
} | |
impl<'a, T, F: FnMut(&T) -> ()> DerefMut for MutBorrow<'a, T, F> { | |
fn deref_mut(&mut self) -> &mut Self::Target { | |
&mut self.0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment