Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Created July 26, 2020 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aboglioli/2789fd72a60b0107590ea09cc844eb44 to your computer and use it in GitHub Desktop.
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.
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