Skip to content

Instantly share code, notes, and snippets.

@elycruz
Created May 25, 2024 22:39
Show Gist options
  • Save elycruz/245ee0530d96a05626b292a4fdf4e3da to your computer and use it in GitHub Desktop.
Save elycruz/245ee0530d96a05626b292a4fdf4e3da to your computer and use it in GitHub Desktop.
Function and Closure references as values in struct
/// Demonstrates an approach for accepting different types of functions, with different lifetimes
/// as struct values.
type MyFn = dyn Fn();
struct ContainsFns<'a> {
other_fn: &'a MyFn,
fns: Option<Vec<&'a MyFn>>
}
trait RunsFns {
fn run_fns(&self);
}
impl RunsFns for ContainsFns<'_> {
fn run_fns(&self) {
(self.other_fn)();
self.fns.as_deref().map(|fns| fns.into_iter().for_each(|f| f()));
}
}
fn hello() {
println!("Hello 1");
}
fn main() {
let fn_one = || println!("Hello 1.2");
let fn_two = || println!("Hello 1.3");
let t = ContainsFns {
other_fn: &hello,
fns: None,
};
let t2 = ContainsFns {
other_fn: &fn_two,
fns: Some(vec![
&hello,
&fn_one,
&fn_two,
&|| println!("Hello 1.4")
])
};
t.run_fns();
t2.run_fns();
hello();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment