在下面的代码中,我试图传递 Option<FnOnce(&mut Thing)>
到高阶函数 invoke_me_maybe()
.如果被传递的函数存在,它将被调用,否则不被调用。Option<FnOnce(&mut Thing)>
使用 as_some()
构建从 bool 值的其他特征方法中,复制了 boolinator箱。
struct Thing{}
fn invoke_me_maybe<F: FnOnce(&mut Thing)>(t: &mut Thing, opt_f: Option<F>) {
if let Some(f) = opt_f {
f(t);
}
}
trait BoolOption {
fn as_some<T>(self, some: T) -> Option<T>;
}
impl BoolOption for bool {
fn as_some<T>(self, some: T) -> Option<T> {
if self { Some(some) } else { None }
}
}
pub fn main() {
let mut thing = Thing{};
invoke_me_maybe(&mut thing, true.as_some(|t| {}));
}
invoke_me_maybe()
功能不保留opt_f
超出函数的末尾,因此我们不需要将函数包装在 Box 或类似的东西中。产生的错误如下:
error[E0631]: type mismatch in closure arguments
--> src/main.rs:21:33
|
3 | fn invoke_me_maybe<F: FnOnce(&mut Thing)>(t: &mut Thing, opt_f: Option<F>) {
| --------------- ------------------ required by this bound in `invoke_me_maybe`
...
21 | invoke_me_maybe(&mut thing, true.as_some(|t| {}));
| ^^^^^^^^^^^^^---^^^^
| | |
| | found signature of `fn(_) -> _`
| expected signature of `for<'r> fn(&'r mut Thing) -> _`
error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:21:46: 21:52] as std::ops::FnOnce<(&'r mut Thing,)>>::Output == ()`
--> src/main.rs:21:5
|
3 | fn invoke_me_maybe<F: FnOnce(&mut Thing)>(t: &mut Thing, opt_f: Option<F>) {
| --------------- ------------------ required by this bound in `invoke_me_maybe`
...
21 | invoke_me_maybe(&mut thing, true.as_some(|t| {}));
| ^^^^^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0271, E0631.
For more information about an error, try `rustc --explain E0271`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
我可能缺少一些明确的生命周期参数或类似的东西,但我无法弄清楚。不是
fn(_) -> _
已与 for<'r> fn(&'r mut Thing) -> _
匹配?
最佳答案
使用闭包作为高阶函数是很棘手的。我注意到显式编写参数的类型通常会有所帮助。在你的情况下 does the trick :
invoke_me_maybe(&mut thing, true.as_some(|t: &mut Thing| {}));
问题似乎是
invoke_me_maybe
采用具有多种可能性的通用参数,而 |t| {}
可能意味着任何东西,编译器无法同时匹配两者。在这种情况下,添加类型注释会有所帮助。我个人认为这是一个编译器错误,但我之前错了......
关于rust - 预期绑定(bind)生命周期参数,在尝试传递 Option<FnOnce> 时找到具体生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61674041/