Created
July 26, 2020 23:30
-
-
Save aboglioli/2789fd72a60b0107590ea09cc844eb44 to your computer and use it in GitHub Desktop.
Simple example of using an array of FnMut to execute inner code inside a trait object.
This file contains hidden or 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
pub trait Executor { | |
fn run(&mut self, f: &mut dyn FnMut(i32) -> i32); | |
} | |
struct SimpleExecutor { | |
v: i32, | |
} | |
impl Executor for SimpleExecutor { | |
fn run(&mut self, f: &mut dyn FnMut(i32) -> i32) { | |
self.v = f(self.v); | |
} | |
} | |
fn use_executor<E: Executor, F: FnMut(i32) -> i32>(e: &mut E, mut f: F) { | |
e.run(&mut f); | |
} | |
fn main() { | |
let mut exec = SimpleExecutor { v: 2 }; | |
let mut ext = 0; | |
{ | |
let mut fns: Vec<Box<dyn FnMut(i32) -> i32>> = vec![ | |
Box::new(|x| { | |
ext += 1; | |
x + 1 | |
}), | |
Box::new(|x| x * 2), | |
Box::new(|x| x * 3), | |
]; | |
for func in fns.iter_mut() { | |
use_executor(&mut exec, func); | |
} | |
} | |
println!("{}", exec.v); | |
println!("{}", ext); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment