簡體   English   中英

作為函數參數的閉包“由於需求沖突而無法推斷出適當的壽命”

[英]Closure as function parameter “cannot infer an appropriate lifetime due to conflicting requirements”

我正在嘗試使用閉包作為函數參數:

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

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

但我得到這個終身錯誤:

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

我不明白為什么不能正確推斷壽命。 我該怎么解決?

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

如果要使用盒裝閉合,則需要使用move || {} move || {}

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

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

另一方面,您不能直接使用未裝箱的封閉盒,因為它可能包含任何數量的捕獲元素,因此大小不一。 通過使用泛型,您可以輕松繞開此限制:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM