为什么"|_|1"不能满足使用寿命要求



我有以下特点和Fn的通用实现:

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<'a> Provider<'a, Out = usize>。然而,最简单的闭包|_| 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>,
|                             ^^^^^^^^^^^

游乐场链接

有人能解释一下错误消息的含义以及如何让代码正常工作吗?

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

assert_usize_provider(|_ : &State| 1);

最新更新