gpt4 book ai didi

rust - 为什么 `|_| 1`不满足生存期要求

转载 作者:行者123 更新时间:2023-12-04 15:01:40 26 4
gpt4 key购买 nike

我对 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>,
| ^^^^^^^^^^^

Playground link

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

最佳答案

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

assert_usize_provider(|_ : &State| 1);

关于rust - 为什么 `|_| 1`不满足生存期要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66847019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com