如何为包含闭包的结构创建构造函数?

use*_*708 6 rust

我将如何实现一个方法作为包含闭包的结构的构造函数?我是Rust的新手,关于封装正在积极开展的工作,我很难在文档中找到解决方案.

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);
}
Run Code Online (Sandbox Code Playgroud)

这是我能够在不遇到大量问题的情况下获得的.我似乎无法创建一个A::new()接受闭包作为参数的版本,使用该参数创建一个类型的结构A,然后返回新创建的结构.有没有办法做到这一点,或者如果没有,我不理解什么?

huo*_*uon 6

闭包被视为一种通用的; 通常使用类型参数名称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
}
Run Code Online (Sandbox Code Playgroud)

通常,您会看到impl将通用限制为特定类型的闭包的类型或块的限制:

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 }
    }
}
Run Code Online (Sandbox Code Playgroud)