Created
September 20, 2019 21:13
-
-
Save rust-play/a636d2c7e3d5ad506b4934738d342b29 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 vec = OnUpdate(vec![], |v| { | |
println!("Vec updated: {:?}", v); | |
}); | |
vec.borrow_mut().push(5); | |
vec.borrow_mut().push(6); | |
vec.borrow_mut().push(7); | |
let mut int = OnUpdate(10, |v| { | |
println!("Int updated: {:?}", v); | |
}); | |
*int.borrow_mut() += 5; | |
} | |
#[derive(Debug, Clone, Copy)] | |
struct OnUpdate<T, F: Fn(&T) -> ()>(T, F); | |
impl<T, F: Fn(&T) -> ()> OnUpdate<T, F> { | |
fn borrow_mut(&mut self) -> MutBorrow<T, F> { | |
MutBorrow(&mut self.0, &self.1) | |
} | |
} | |
#[derive(Debug)] | |
struct MutBorrow<'a, T, F: Fn(&T) -> ()>(&'a mut T, &'a F); | |
impl<'a, T, F: Fn(&T) -> ()> Drop for MutBorrow<'a, T, F> { | |
fn drop(&mut self) { | |
(self.1)(&self.0) | |
} | |
} | |
impl<'a, T, F: Fn(&T) -> ()> Deref for MutBorrow<'a, T, F> { | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
&self.0 | |
} | |
} | |
impl<'a, T, F: Fn(&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