这里有一个(有点做作)的例子来说明我想做些什么
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>;
}