如果我已经将特征边界添加到另一个 impl 块,为什么还需要在 impl 块上添加特征边界?

Why do I need to add trait bounds on impl blocks if I've already added them to another impl block?

我有以下代码:

use std::ops::Div;
use std::ops::Mul;

#[derive(Debug)]
struct Foo<T> {
    bar: T,
}

impl<T> Foo<T>
where
    T: Div<Output = T> + Copy,
{
    fn new(bar: T) -> Foo<T> {
        let baz = Foo::baz(bar);
        Foo { bar: bar / baz }
    }
    fn baz(bar: T) -> T {
        unimplemented!();
    }
}

impl<T> Mul for Foo<T>
where
    T: Mul<Output = T>,
{
    type Output = Foo<T>;

    fn mul(self, other: Foo<T>) -> Foo<T> {
        Foo::new(self.bar * other.bar)
    }
}

然而,编译器报错:

error[E0277]: cannot divide `T` by `T`
  --> src/main.rs:29:9
   |
29 |         Foo::new(self.bar * other.bar)
   |         ^^^^^^^^ no implementation for `T / T`
   |
   = help: the trait `std::ops::Div` is not implemented for `T`
   = help: consider adding a `where T: std::ops::Div` bound
note: required by `<Foo<T>>::new`
  --> src/main.rs:13:5
   |
13 |     fn new(bar: T) -> Foo<T> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^

error[E0277]: the trait bound `T: std::marker::Copy` is not satisfied
  --> src/main.rs:29:9
   |
29 |         Foo::new(self.bar * other.bar)
   |         ^^^^^^^^ the trait `std::marker::Copy` is not implemented for `T`
   |
   = help: consider adding a `where T: std::marker::Copy` bound
note: required by `<Foo<T>>::new`
  --> src/main.rs:13:5
   |
13 |     fn new(bar: T) -> Foo<T> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^

这可以通过以下修改解决:

impl<T> Mul for Foo<T>
where
    T: Mul<Output = T> + Div<Output = T> + Copy,

为什么我需要将 Div<Output = T>Copy 添加到 Mul for Foo<T>?不应该 Foo<T> 已经满足边界,因为:

impl<T> Foo<T>
where
    T: Div<Output = T> + Copy,

每个 impl 块彼此完全不同,包括它们的特征边界——一个 impl 块具有约束这一事实对其他块没有任何意义。

在这种情况下,你的 impl 特征块 Mul 并不真的 需要 Div 特征,因为它可以直接构建 Foo

impl<T> Mul for Foo<T>
where
    T: Mul<Output = T>,
{
    type Output = Foo<T>;

    fn mul(self, other: Foo<T>) -> Foo<T> {
        Foo { bar: self.bar * other.bar }
    }
}

只是因为您选择了调用 Foo::new(它具有 DivCopy 要求),所以您的 Mul 的原始版本将无法编译。这在概念上与这个普通函数的问题相同,它也不需要 CopyDiv:

fn x<T>(a: T) -> Foo<T> {
    Foo::new(a)
}

请注意,我说的是“impl 阻止”,而不是 "inherent impl block" 或 "trait impl block"。您可以有多个具有不同边界的固有 impl 块:

impl<T> Vec<T> {
    pub fn new() -> Vec<T> { /* ... */ }
}

impl<T> Vec<T>
where
    T: Clone,
{
    pub fn resize(&mut self, new_len: usize, value: T) { /* ... */ }
}

这允许类型具有仅在满足特定条件时才适用的函数。

另请参阅:

  • Is it better to specify trait bound on the impl block or on the method?