Skip to content

Instantly share code, notes, and snippets.

@kolen
Created April 19, 2019 00:29
Show Gist options
  • Save kolen/0ecddef2b07fa9ba78aa00140b080433 to your computer and use it in GitHub Desktop.
Save kolen/0ecddef2b07fa9ba78aa00140b080433 to your computer and use it in GitHub Desktop.
use std::boxed::Box;
use std::thread;
use std::mem;
trait Callback: Send {
fn callback(&mut self);
}
struct CallbackHolder<CB: Callback> {
userdata: Box<Option<CB>>
}
fn open<F, CB>(get_callback: F) -> CallbackHolder<CB>
where F: FnOnce() -> CB, CB: Callback {
let mut userdata: Box<Option<CB>> = Box::new(None);
*userdata = Some(get_callback());
CallbackHolder { userdata }
}
struct MyCallback<'a> {
data: &'a String,
}
impl<'a> Callback for MyCallback<'a> {
fn callback(&mut self) {
println!("{}", self.data);
}
}
fn main() {
let mut opt = Some(String::from("foobar"));
let callback_holder = if let Some(ref data) = opt {
let my_callback = MyCallback { data };
open(|| { my_callback })
} else {
panic!()
};
opt = None;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment