为闭包实现特征会导致绑定/具体生命周期不匹配 [英] Implementing a trait for closures results in bound/concrete lifetime mismatch

查看:64
本文介绍了为闭包实现特征会导致绑定/具体生命周期不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为特定类型的闭包实现特征.这是一个最小的示例(游乐场):

I want to implement a trait for closures of a specific type. Here is a minimal example (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子句中:

I already tried to explicitly add the HRTB to the where clause like this:

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

但这没有帮助.我也用impl块声明了生存期,如下所示:

But it didn't help. I also declared the lifetime on the impl block instead, like this:

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

但是这会导致impl块中的生命周期错误.我认为这些错误是正确的,并且不能在impl块上声明lifetime参数.

But this results in a lifetime error within the impl block. I think that those errors are right and the lifetime parameter can't be declared on the impl block.

如何解决此示例?

推荐答案

检查此部分错误:

[...]实现特征std::ops::Fn<(_,)>,但是特征for<'r> std::ops::Fn<(&'r u32,)>是必需的

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

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

I think that basically there's not enough code to allow types to be properly inferred. Adding an explicit type annotation allows the example to be compiled:

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

这篇关于为闭包实现特征会导致绑定/具体生命周期不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆