Skip to content

Instantly share code, notes, and snippets.

@billyfbrain
Last active May 25, 2019 12:00
Show Gist options
  • Select an option

  • Save billyfbrain/12bfadaf305913eb66d669fa0517ac8f to your computer and use it in GitHub Desktop.

Select an option

Save billyfbrain/12bfadaf305913eb66d669fa0517ac8f to your computer and use it in GitHub Desktop.
Callback in struct
struct Foo {
callback: Option<Box<dyn Fn()>>,
}
impl Foo {
fn new() -> Self {
Self {
callback: None,
}
}
fn set_callback<C>(&mut self, cb: C)
where
C: Fn() + 'static,
{
self.callback = Some(Box::new(cb));
}
fn call_callback(&self) {
self.callback.as_ref().map(|cb|cb());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment