【问题标题】:Expected bound lifetime parameter, found concrete lifetime when trying to pass an Option<FnOnce>预期绑定生命周期参数,在尝试传递 Option<FnOnce> 时找到具体生命周期
【发布时间】:2020-05-08 07:21:07
【问题描述】:

在下面的代码中,我试图将Option&lt;FnOnce(&amp;mut Thing)&gt; 传递给高阶函数invoke_me_maybe()。被传递的函数如果存在就会被调用,否则不会被调用。

Option&lt;FnOnce(&amp;mut Thing)&gt; 是使用 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(_) -&gt; _ 不是已经和for&lt;'r&gt; fn(&amp;'r mut Thing) -&gt; _ 匹配了吗?

【问题讨论】:

    标签: rust lifetime higher-order-functions


    【解决方案1】:

    使用闭包作为高阶函数是很棘手的。我注意到显式编写参数的类型通常会有所帮助。你的情况是does the trick:

        invoke_me_maybe(&mut thing, true.as_some(|t: &mut Thing| {}));
    

    问题似乎是invoke_me_maybe 采用了一个有很多可能性的通用参数,而|t| {} 可能意味着任何东西,编译器无法同时匹配两者。在这种情况下,添加类型注释会有所帮助。

    我个人认为这是一个编译器错误,但我之前一直错...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      相关资源
      最近更新 更多