I am trying to use a callback that uses the self parameter of an object. The part that prevents this from compiling is the self.make_sandwhich() bit. How can I do something like this and have it actually compile in rust? The objective is to make ThingUser able to specify functionality for a Thing. In this case, when you junk the potato, the user makes a sandwhich.
pub trait Thing {
fn stuff(&self);
fn junk(&mut self);
}
pub struct Potato {
thing: Box<dyn FnMut()+Send>,
}
impl Potato {
fn new() -> Self {
Self{
thing: Box::new(||{println!("Original callback");}),
}
}
fn give_callback(&mut self, thing: Box<dyn FnMut()+Send>) {
self.thing = thing;
}
}
impl Thing for Potato {
fn stuff(&self) {
}
fn junk(&mut self) {
(self.thing)();
}
}
fn make_thing() -> Box<dyn Thing> {
Box::new(Potato::new())
}
pub trait ThingUser {
fn get_thing(&mut self) -> Option<Box<dyn Thing>>;
}
pub struct Person {
}
impl Person {
fn make_sandwhich(&self) {
println!("I made a sandwhich");
}
}
impl ThingUser for Person {
fn get_thing(&mut self) -> Option<Box<dyn Thing>> {
let mut p = Potato::new();
p.give_callback(Box::new(||{self.make_sandwhich()}));
Some(Box::new(p))
}
}
fn main() {
println!("Hello, world!");
let mut p = Potato::new();
p.stuff();
p.give_callback(Box::new(||{println!("Callback");}));
(p.thing)();
p.junk();
let mut q = make_thing();
q.junk();
let mut tu = Person{};
let used_thing = tu.get_thing();
used_thing.unwrap().junk();
}