gpt4 book ai didi

rust - 实现闭包特征会导致绑定(bind)/具体生命周期不匹配

转载 作者:行者123 更新时间:2023-11-29 07:45:30 25 4
gpt4 key购买 nike

我想为特定类型的闭包实现一个特征。这是一个最小的例子(playground):

trait Foo {
fn foo(&self, x: &u32);
}

impl<F> Foo for F
where F: Fn(&u32)
{
fn foo(&self, x: &u32) {
self(x)
}
}

fn main() {
let _: &FnOnce(&u32) = &|x| {}; // works
let _: &Foo = &|x| {}; // doesn't work
}

它导致了这个错误:

error: type mismatch resolving `for<'r> <[closure@<anon>:16:29: 16:35] as std::ops::FnOnce<(&'r u32,)>>::Output == ()`:
expected bound lifetime parameter ,
found concrete lifetime [--explain E0271]
--> <anon>:16:28
|>
16 |> let _: &Foo = &|x| {};
|> ^^^^^^^
note: required because of the requirements on the impl of `Foo` for `[closure@<anon>:16:29: 16:35]`
note: required for the cast to the object type `Foo`

error: type mismatch: the type `[closure@<anon>:16:29: 16:35]` implements the trait `std::ops::Fn<(_,)>`, but the trait `for<'r> std::ops::Fn<(&'r u32,)>` is required (expected concrete lifetime, found bound lifetime parameter ) [--explain E0281]
--> <anon>:16:28
|>
16 |> let _: &Foo = &|x| {};
|> ^^^^^^^
note: required because of the requirements on the impl of `Foo` for `[closure@<anon>:16:29: 16:35]`
note: required for the cast to the object type `Foo`

我已经尝试将 HRTB 显式添加到 where 子句中,如下所示:

where F: for<'a> Fn(&'a u32)

但这并没有帮助。我还在 impl block 上声明了生命周期,如下所示:

impl<'a, F> Foo for F
where F: Fn(&'a u32) { ... }

但这会导致 impl block 中的生命周期错误。我认为那些错误是正确的,不能在 impl block 上声明生命周期参数。

我该如何修正这个例子?

最佳答案

检查这部分错误:

[...] implements the trait std::ops::Fn<(_,)>, but the trait for<'r> std::ops::Fn<(&'r u32,)> is required

我认为基本上没有足够的代码来正确推断类型。添加显式类型注释允许编译示例:

let _: &Foo          = &|x: &u32| {};

关于rust - 实现闭包特征会导致绑定(bind)/具体生命周期不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39356633/

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