【问题标题】:How to pass a function as argument in Rust如何在 Rust 中将函数作为参数传递
【发布时间】:2015-01-20 17:21:13
【问题描述】:

鉴于以下 rust 程序:

fn call_twice<A>(val: A, f: fn(A) -> A) -> A {
    f(f(val))
}

fn main() {
    fn double(x: int) -> int {x + x};
    println!("Res is {}", call_twice(10i, double));
    // println!("Res is {}", call_twice(10i, (x: int) -> int {x + x}));
    // ^ this line will fail
}

为什么我可以将double 作为函数传递,但不能内联?什么是实现相同行为而不在某处定义函数的好方法?

【问题讨论】:

    标签: function parameter-passing rust


    【解决方案1】:

    2016-04-01 更新:

    从 Rust 1.0 开始,代码应如下所示:

    fn call_twice<A, F>(val: A, mut f: F) -> A
    where F: FnMut(A) -> A {
        let tmp = f(val);
        f(tmp)
    }
    
    fn main() {
        fn double(x: i32) -> i32 {x + x};
        println!("Res is {}", call_twice(10, double));
        println!("Res is {}", call_twice(10, |x| x + x));
    }
    

    对闭包参数的更改是因为闭包现在已取消装箱。

    原文:

    据我所知,你不能像那样定义内联函数。

    想要的是一个闭包。以下作品:

    fn call_twice<A>(val: A, f: |A| -> A) -> A {
        let tmp = f(val);
        f(tmp)
    }
    
    fn main() {
        fn double(x: int) -> int {x + x};
        println!("Res is {}", call_twice(10i, double));
        println!("Res is {}", call_twice(10i, |x| x + x));
    }
    

    有几点需要注意:

    1. 函数强制执行闭包,但反之则不然。

    2. 由于借用规则,您需要将f(val) 的结果临时存储。简短版本:您需要对闭包的唯一访问才能调用它,而借用检查器还不够聪明,无法意识到这两个调用在其原始位置上是独立的。

    3. 闭包正在被未装箱的闭包所取代,因此这将在未来发生变化,但我们还没有完全做到。

    【讨论】:

    • 感谢您的解释。临时变量有点奇怪,但我认为这将在更稳定的版本中修复。
    • 这似乎不适用于 rust 1.7:play.rust-lang.org/…
    • @SandeepDatta 这个答案来自 2014 年;即使在 Rust 1.0 中,此代码也是无效的。我已经更新了。
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多