通用特征实现错误

Generic trait implementation errors

这个特性声明和定义可以正常工作,没有任何问题:

trait FTrait<T>: Fn(T, T) -> T {}
impl<T, F> FTrait<T> for F where F: Fn(T, T) -> T, {}
...
fn hof(f: impl FTrait<u32>) -> impl FTrait<u32> { //fourth with a generic trait in use with concrete types
    move |a, b| {
        let r = f(a, b);
        r
    }
}

但是这个特征声明给出了多个错误:

    trait FTraitBorrowed<'a, T>: Fn(&'a T, &'a T) -> &'a T {}
    impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}

....
fn hof_borrowed(f: impl FTraitBorrowed<i32>) -> impl FTraitBorrowed<i32 > {
    move |a, b| {
        let r = f(a, b);
        r
    }

此处列出了错误:

Errors:
error: associated type bindings must be declared after generic parameters
  --> src\main.rs:44:31
   |
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
   |                               ^^^^-----^^^
   |                                   |
   |                                   this associated type binding should be moved after the generic parameters

error[E0658]: associated type bounds are unstable
  --> src\main.rs:44:35
   |
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
   |                                   ^^^^^
   |
   = note: for more information, see https://github.com/rust-lang/rust/issues/52662

error[E0229]: associated type bindings are not allowed here
  --> src\main.rs:44:35
   |
44 | impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> for F where F: Fn(&'a T, &T) -> &'a T, {}
   |                                   ^^^^^ associated type not allowed here

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0229, E0658.
For more information about an error, try `rustc --explain E0229`.

无法从提示中清楚地理解错误。

为了消除第一个错误,如果我在实现中像这样交换 F 和 T 的位置:

impl<'a, T, F> FTraitBorrowed<'a, F, T: 'a, > ...

有人可以帮忙吗?

谢谢。

导致错误的问题是那里不允许类型界限:

// correct
impl<'a, T: 'a, F> FTraitBorrowed<'a, T, F> ...

// wrong
impl<'a, T, F> FTraitBorrowed<'a, T: 'a, F> ...

因此,Rust 认为您正在使用不稳定的功能 associated type bounds,这导致了令人困惑的错误消息。

还有一些其他问题,我设法解决了 (playground):

trait FTraitBorrowed<'a, T: 'a>: Fn(&'a T, &'a T) -> &'a T {}

impl<'a, T: 'a, F> FTraitBorrowed<'a, T> for F where F: Fn(&'a T, &'a T) -> &'a T {}

fn hof_borrowed<'a, F>(f: impl FTraitBorrowed<'a, i32>) -> impl FTraitBorrowed<'a, i32> {
    move |a, b| f(a, b)
}