Skip to content

Instantly share code, notes, and snippets.

@green-coder
Last active September 17, 2016 19:39
Show Gist options
  • Save green-coder/689f49d961deaea6ed4e3d92368233d1 to your computer and use it in GitHub Desktop.
Save green-coder/689f49d961deaea6ed4e3d92368233d1 to your computer and use it in GitHub Desktop.
struct ApplyFnToParam<F> {
f: F,
param: u32
}
fn my_default_fn(param: u32) -> bool {
param == 42
}
// This is the part which blocked me the whole day, and I finally figured it out myself.
// I don't know if I should cry or laugh.
impl ApplyFnToParam<fn(u32) -> bool> {
fn new_with_default_fn(param: u32) -> ApplyFnToParam<fn(u32) -> bool> {
ApplyFnToParam {
f: my_default_fn as fn(u32) -> bool,
param: param
}
}
}
impl<F> ApplyFnToParam<F> where F: Fn(u32) -> bool {
fn new(f: F, param: u32) -> ApplyFnToParam<F> {
ApplyFnToParam {
f: f,
param: param
}
}
fn apply(self) -> bool {
(self.f)(self.param)
}
}
fn main() {
let a = ApplyFnToParam::new(my_default_fn, 7).apply();
let b = ApplyFnToParam::new(|x| x == 42, 42).apply();
let c = ApplyFnToParam::new_with_default_fn(42).apply();
println!("{} {} {}", a, b, c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment