在相关的特征类型的约束

问题描述 投票:6回答:1

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

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

我记得读一些有关的特征(当时未实现),将允许更丰富的约束这样的事情,但我不记得它的名字,并不能找到它。

rust associated-types
1个回答
9
投票

Graph的定义,你可以限制每个关联类型的关联类型(!)等于在Graph对应的相关类型。

pub trait Graph {
    type Node: Node<Edge = Self::Edge>;
    type Edge: Edge<Node = Self::Node>;
    fn get_nodes(&self) -> Vec<Self::Node>;
}
© www.soinside.com 2019 - 2024. All rights reserved.