【问题标题】:Why does `|_| 1` not meet lifetime requirements为什么`|_| 1`不满足寿命要求
【发布时间】:2021-03-28 23:12:06
【问题描述】:

我对@9​​87654322@ 具有以下特征和通用实现:

trait Provider<'a> {
    type Out;
    fn get(&'a self, state: &State) -> Self::Out;
}

impl<'a, F, T> Provider<'a> for F
where
    F: Fn(&State) -> T,
{
    type Out = T;

    fn get(&'a self, state: &State) -> T {
        self(state)
    }
}

现在,我有一些需要for&lt;'a&gt; Provider&lt;'a, Out = usize&gt; 的代码。但是,最简单的闭包 |_| 1 不符合条件,而是提供了以下我不理解的错误消息:

fn assert_usize_provider<P>(_: P)
where
    P: for<'a> Provider<'a, Out = usize>,
{
}

fn main() {
    assert_usize_provider(|_| 1);
}
error[E0308]: mismatched types
  --> src/main.rs:27:5
   |
27 |     assert_usize_provider(|_| 1);
   |     ^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected type `FnOnce<(&State,)>`
              found type `FnOnce<(&State,)>`
note: this closure does not fulfill the lifetime requirements
  --> src/main.rs:27:27
   |
27 |     assert_usize_provider(|_| 1);
   |                           ^^^^^
note: the lifetime requirement is introduced here
  --> src/main.rs:22:29
   |
22 |     P: for<'a> Provider<'a, Out = usize>,
   |                             ^^^^^^^^^^^

Playground link

有人可以解释该错误消息的含义以及如何使该代码正常工作吗?

【问题讨论】:

  • 这感觉像是早绑定/晚绑定的生命周期问题,在另一个问题中是'a'a: 'a 之间的区别......有人知道我在说什么吗?跨度>

标签: rust closures traits lifetime


【解决方案1】:

我不知道为什么推理在这种情况下不起作用,但您可以添加类型注释以使代码正常工作。

assert_usize_provider(|_ : &State| 1);

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 2021-04-02
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2017-11-27
    相关资源
    最近更新 更多