作为函数参数的闭合“由于需求冲突而不能推断出适当的寿命". [英] Closure as function parameter "cannot infer an appropriate lifetime due to conflicting requirements"

查看:93
本文介绍了作为函数参数的闭合“由于需求冲突而不能推断出适当的寿命".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用闭包作为函数参数:

I am trying to use a closure as function parameter:

fn foo(f: Box<Fn() -> bool>) -> bool {
    f()
}

fn main() {
    let bar = 42;
    foo(Box::new(|| bar != 42));
}

但是我收到这个终身错误:

but I get this lifetime error:

src/main.rs:7:24: 7:36 error: cannot infer an appropriate lifetime due to conflicting requirements
src/main.rs:7   let n = foo(Box::new(|| bar != 42));
                                     ^~~~~~~~~~~~
src/main.rs:7:15: 7:23 note: first, the lifetime cannot outlive the     expression at 7:14...
src/main.rs:7   let n = foo(Box::new(|| bar != 42));
                            ^~~~~~~~
src/main.rs:7:15: 7:23 note: ...so that the type `[closure src/main.rs:7:24: 7:36]` will meet its required lifetime bounds
src/main.rs:7   let n = foo(Box::new(|| bar != 42));
                            ^~~~~~~~
src/main.rs:7:15: 7:37 note: but, the lifetime must be valid for the call at 7:14...
src/main.rs:7   let n = foo(Box::new(|| bar != 42));
                            ^~~~~~~~~~~~~~~~~~~~~~
src/main.rs:7:24: 7:36 note: ...so that argument is valid for the call
src/main.rs:7   let n = foo(Box::new(|| bar != 42));
                                     ^~~~~~~~~~~~
error: aborting due to previous error

我不明白为什么不能正确推断寿命.我该怎么做才能解决这个问题?

I don't understand why the lifetime is not properly infered. What can I do to fix that ?

$ rustc --version
rustc 1.0.0-nightly (6c065fc8c 2015-02-17) (built 2015-02-18)

推荐答案

如果要使用盒装封盖,则需要使用move || {}.

if you want to use a boxed closure you need to use move || {}.

fn foo(f: Box<Fn() -> bool>)
       -> bool {
    f()
}

fn main() {
    let bar = 42;
    let blub = foo(Box::new(move || bar != 42));
}

另一方面,您不能直接使用未装箱的封闭盒,因为它可能包含任何数量的捕获元素,因此大小不一.通过使用泛型,您可以轻松绕开此限制:

On the other hand, you cannot use an unboxed closure directly, as it may contain any number of captured elements, and is therefor unsized. By using generics you can easily circumvent this limitation:

fn foo<T>(f: T)
          -> bool
          where T : Fn() -> bool {
    f()
}

fn main() {
    let bar = 42;
    let blub = foo(|| bar != 42);
}

这篇关于作为函数参数的闭合“由于需求冲突而不能推断出适当的寿命".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆