【发布时间】:2020-05-08 07:21:07
【问题描述】:
在下面的代码中,我试图将Option<FnOnce(&mut Thing)> 传递给高阶函数invoke_me_maybe()。被传递的函数如果存在就会被调用,否则不会被调用。
Option<FnOnce(&mut Thing)> 是使用 as_some() 从布尔值的附加特征方法构造的,复制了 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) -> _ 匹配了吗?
【问题讨论】:
标签: rust lifetime higher-order-functions