【问题标题】:How would you create a constructor for a struct containing a closure?您将如何为包含闭包的结构创建构造函数?
【发布时间】:2013-11-12 05:22:41
【问题描述】:

我将如何实现一个方法,该方法充当包含闭包的结构的构造函数?我是 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);
}

这是我所能做到的,不会遇到很多问题。我似乎无法创建一个接受闭包作为参数的A::new() 版本,使用该参数创建A 类型的结构,然后返回新创建的结构。有没有办法做到这一点,或者如果没有,我不明白什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    闭包被视为一种泛型;常用类型参数名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
    }
    

    您通常会看到类型限制或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 }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 2017-09-20
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多