) -> bool { f() } fn main() { let bar = 42; foo(Box:-6ren">
gpt4 book ai didi

closures - 闭包作为函数参数 "cannot infer an appropriate lifetime due to conflicting requirements"

转载 作者:行者123 更新时间:2023-11-29 08:25:41 24 4
gpt4 key购买 nike

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

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 || {}

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);
}

关于closures - 闭包作为函数参数 "cannot infer an appropriate lifetime due to conflicting requirements",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com