为什么有必要添加冗余特征边界,即使我的特征使用那些相同的特征作为边界?

Why is it necessary to add redundant trait bounds even though my trait uses those same traits as bounds?

我一直在尝试编写一个特性,它需要一个类型来实现 Add(以及进一步向下行的向量空间的其他操作)及其引用。下面是一个小例子,说明我运行进入的问题:

use std::ops::Add;

#[derive(Debug)]
struct MyVec<T>(Vec<T>);

impl<'a, 'b, T: Copy + Add> Add<&'a MyVec<T>> for &'b MyVec<T> {
    type Output = MyVec<T::Output>;
    fn add(self, other: &'a MyVec<T>) -> Self::Output {
        /* ... */
    }
}
impl<'a, T: Copy + Add> Add<MyVec<T>> for &'a MyVec<T> {
    /* ... */
}
impl<'a, T: Copy + Add> Add<&'a MyVec<T>> for MyVec<T> {
    /* ... */
}
impl<T: Copy + Add> Add<MyVec<T>> for MyVec<T> {
    /* ... */
}

trait Addable: Add<Self, Output = Self>
where
    Self: Sized,
    for<'a> &'a Self: Add<Self, Output = Self>,
    for<'b> Self: Add<&'b Self, Output = Self>,
    for<'a, 'b> &'a Self: Add<&'b Self, Output = Self>,
{
}

impl<T: Copy + Add<Output = T>> Addable for MyVec<T> {}

fn add_stuff<'a, 'b, T: Addable>(x: &'a T, y: &'b T) -> T {
    x + y
}

fn main() {
    let v = MyVec(vec![1, 2, 3]);
    let w = MyVec(vec![2, 4, 6]);
    println!("{:?}", add_stuff(&v, &w));
}

但是,我收到以下编译器错误:

error[E0277]: the trait bound `for<'a> &'a T: std::ops::Add<T>` is not satisfied
  --> src/main.rs:33:1
   |
33 | / fn add_stuff<'a, 'b, T: Addable>(x: &'a T, y: &'b T) -> T {
34 | |     x + y
35 | | }
   | |_^ no implementation for `&'a T + T`
   |
   = help: the trait `for<'a> std::ops::Add<T>` is not implemented for `&'a T`
   = help: consider adding a `where for<'a> &'a T: std::ops::Add<T>` bound
   = note: required by `Addable`

error[E0277]: the trait bound `for<'a, 'b> &'a T: std::ops::Add<&'b T>` is not satisfied
  --> src/main.rs:33:1
   |
33 | / fn add_stuff<'a, 'b, T: Addable>(x: &'a T, y: &'b T) -> T {
34 | |     x + y
35 | | }
   | |_^ no implementation for `&'a T + &'b T`
   |
   = help: the trait `for<'a, 'b> std::ops::Add<&'b T>` is not implemented for `&'a T`
   = help: consider adding a `where for<'a, 'b> &'a T: std::ops::Add<&'b T>` bound
   = note: required by `Addable`

这可以通过使用编译器建议的 where 子句修改 add_stuff 函数来解决:

where
    for<'c, 'd> &'c T: Add<&'d T, Output = T>,
    for<'c> &'c T: Add<T, Output = T>,

我不明白为什么这是必要的。我想通过在特性的定义中指定一个界限,我可以依赖于实现该特性的任何类型都满足该界限吗?每次都必须添加这些 where 子句有点违背我的 Addable 特征的全部要点。

谷歌搜索 this GitHub issue 我不完全理解但可能相关?这表明这确实是 Rust 中的一个错误(很长时间没有修复)。

您遇到了 Rust 编译器当前的一个缺点。 RFC 2089 提出让它按你期望的方式工作,并于 2017 年 12 月被接受。

但是,截至今天,该功能尚未实现。 tracking issue for the implementation 还没有看到多少 activity,所以看起来实施甚至还没有开始。在有效实现此特定功能之前,似乎有必要对编译器的特征绑定处理进行一些基本改进(搜索关键字:chalk)。