对关联特征类型的约束

Constraints on associated trait types

这里有一个(有点做作的)例子来说明我想做什么

pub trait Node: Eq + Hash {
    type Edge: Edge;
    fn get_in_edges(&self)  -> Vec<&Self::Edge>;
    fn get_out_edges(&self) -> Vec<&Self::Edge>;
}

pub trait Edge {
    type Node: Node;
    fn get_src(&self) -> &Self::Node;
    fn get_dst(&self) -> &Self::Node;
}

pub trait Graph {
    type Node: Node;
    type Edge: Edge;
    fn get_nodes(&self) -> Vec<Self::Node>;
}

pub fn dfs<G: Graph>(root: &G::Node) {
    let mut stack = VecDeque::new();
    let mut visited = HashSet::new();

    stack.push_front(root);
    while let Some(n) = stack.pop_front() {
        if visited.contains(n) {
            continue
        }
        visited.insert(n);
        for e in n.get_out_edges() {
            stack.push_front(e.get_dst());
        }
    }
}

有没有办法在 Graph 特征中表达 Graph::Node 必须与 Graph::Edge::Node 类型相同,并且 Graph::Edge 必须与 Graph::Node::Edge?

我记得读过一些关于允许对这类事情进行更丰富约束的功能(当时未实现)的内容,但我不记得它的名字也找不到它。

Graph的定义中,可以约束每个关联类型的关联类型(!)等于Graph中对应的关联类型。

pub trait Graph {
    type Node: Node<Edge = Self::Edge>;
    type Edge: Edge<Node = Self::Node>;
    fn get_nodes(&self) -> Vec<Self::Node>;
}