Skip to content

Instantly share code, notes, and snippets.

@AlexanderNenninger
Last active February 20, 2022 15:14
Show Gist options
  • Save AlexanderNenninger/6995d2fd7230fb610e4598487f6ce20e to your computer and use it in GitHub Desktop.
Save AlexanderNenninger/6995d2fd7230fb610e4598487f6ce20e to your computer and use it in GitHub Desktop.
Callback pattern in rust.
use std::boxed::Box;
type Callback = Box<dyn Fn(&mut f64, &f64)>;
type Condition = Box<dyn Fn(&f64, &f64) -> bool>;
type Effect = Box<dyn Fn(&mut f64, &f64)>;
fn step(u: &mut f64, t: &mut f64, callback: &Callback) {
callback(u, t);
*t += 1.;
*u += 1.;
}
fn make_callback(condition: Condition, effect: Effect) -> Callback {
let cb = move |u: &mut f64, t: &f64| {
if condition(u, t) {
effect(u, t)
}
};
Box::new(cb)
}
fn main() {
let u = &mut 0.;
let t = &mut 0.;
let condition: Condition = Box::new(|u: &f64, t: &f64| *u >= 3.);
let effect: Effect = Box::new(|u: &mut f64, t: &f64| *u = 1.);
let cb = make_callback(condition, effect);
for i in 1..9 {
step(u, t, &cb);
println!("u: {0}, t: {1}", u, t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment