使用泛型时是否可以使用自引用关联类型?

Is it possible to use self-referential associated types when using generics?

示例:给定以下特征,

trait DirectedAcyclicGraph<V, E> where V: Add, E: Add

我希望每当 V 类型的值与返回另一个 V 类型的值相同类型的值时。每当将类型 E 的值添加到另一个相同类型的值时,我希望返回另一个 E

我天真地认为这可能是正确的方向,

trait DirectedAcyclicGraph<V, E> where V: Add<Output = V>, E: Add<Output = E>

但这只是瞎猜。

Add 的文档提供了以下示例,

use std::ops::Add;

struct Foo;

impl Add for Foo {
    type Output = Foo;

    fn add(self, _rhs: Foo) -> Foo {
        println!("Adding!");
        self
    }
}

fn main() {
    Foo + Foo;
}

但我无法理解如何以相同的方式为泛型类型提供实现,如果可能的话。

这是一个编程错误的案例。正如@ChrisMorgan 指出的 in his example,表达式 Add<Output = V> 确实可以编译。编译器抱怨的原因是在生产源代码的一个位置 Output = V 没有被一致地添加。

遗憾的是,我在编译压缩MWE时一定也犯了一些错误。

因此,后代的收获是

trait DirectedAcyclicGraph<V, E> where V: Add<Output = V>, E: Add<Output = E>

有效。