Last active
February 20, 2022 15:14
-
-
Save AlexanderNenninger/6995d2fd7230fb610e4598487f6ce20e to your computer and use it in GitHub Desktop.
Callback pattern in rust.
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 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