Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Created May 9, 2020 20:34
Show Gist options
  • Save aboglioli/451067ccca1de3574c283fd6faeb10d6 to your computer and use it in GitHub Desktop.
Save aboglioli/451067ccca1de3574c283fd6faeb10d6 to your computer and use it in GitHub Desktop.
Closures as struct property: using generics and using trait object.
struct Data<F>
where
F: FnMut(&i32) -> i32,
{
value: i32,
dyn_value: i32,
// parser, once assigned, cannot change because each closure is unique
parser: F,
dyn_parser: Box<dyn FnMut(&i32) -> i32>, // dynamic, parser can change any time
}
impl<F> Data<F>
where
F: FnMut(&i32) -> i32,
{
fn exec(&mut self) {
self.value = (self.parser)(&self.value);
}
fn dyn_exec(&mut self) {
self.dyn_value = (self.dyn_parser)(&self.dyn_value);
}
}
fn main() {
let mut d = Data {
value: 2,
dyn_value: 2,
parser: |&x| -> i32 {
x * x
},
dyn_parser: Box::new(|&x| -> i32 {
x * x
}),
};
d.exec();
// parser cannot change
//d.parser = |&x| -> i32 { x + 1 };
d.dyn_exec();
d.dyn_parser = Box::new(|&x| -> i32 { x + 1 }); // can be changed
d.dyn_exec();
println!("- value: {}", d.value);
println!("- dyn_value: {}", d.dyn_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment