How would I go about implementing a method that acts as a constructor for a struct that contains a closure? I'm new to Rust, and what with closures being actively worked on I'm having a hard time finding a solution in the documentation.
struct A<'self> {
fOne: &'self fn(),
}
impl<'self> A<'self> {
fn new() {
println!("Ideally this would return a struct of type A");
}
}
fn run(f: &fn()) {
f();
}
fn main() {
let apples = 5;
let example = A {
fOne: || {
println!("{} apples on the tree.", apples);
},
};
A::new();
run(example.fOne);
}
This is as far as I can get without running into a host of issues. I can't seem to create a version of A::new()
that accepts a closure as an argument, creates a struct of type A
with that argument, and then returns the newly created struct. Is there a way to do this, or if not, what don't I understand?
Best Solution
Closures are treated as a type of generic; it's common to use the type parameter name
F
:Often you will see a restriction on the type or
impl
block that restrict the generic to a specific type of closure: