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?
Closures are treated as a type of generic; it's common to use the type parameter name F
:
struct A<F> {
f_one: F,
}
impl<'a, F> A<F> {
fn new(f: F) -> Self {
A { f_one: f }
}
}
fn main() {
let apples = 5;
let example = A::new(|| println!("{} apples on the tree.", apples));
(example.f_one)(); // extra parens to disambiguate from calling a method
}
Often you will see a restriction on the type or impl
block that restrict the generic to a specific type of closure:
struct A<F>
where
F: Fn(),
{
f_one: F,
}
impl<'a, F> A<F>
where
F: Fn(),
{
fn new(f: F) -> Self {
A { f_one: f }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With