Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you create a constructor for a struct containing a closure?

Tags:

rust

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?

like image 917
user2981708 Avatar asked Nov 12 '13 05:11

user2981708


1 Answers

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 }
    }
}
like image 170
huon Avatar answered Nov 15 '22 08:11

huon