关联特征类型的约束 [英] Constraints on associated trait types
问题描述
这是一个(有些人为设计的)例子,用来说明我想做的事
Here's a (somewhat contrived) example to illustrate what I would like to do
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
相同的类型?
Is there a way to express in the Graph
trait that Graph::Node
must be the same type as Graph::Edge::Node
and that Graph::Edge
must be the same type as Graph::Node::Edge
?
我记得阅读过有关某个功能的信息(当时尚未实现),该功能将允许对此类功能进行更丰富的约束,但是我不记得它的名称,也找不到它.
I remember reading something about a feature (not implemented at the time) that would allow richer constraints for this sort of thing, but I don't remember its name and cannot find it.
推荐答案
在Graph
的定义中,可以将每个关联类型的关联类型(!)约束为等于Graph
中的相应关联类型./p>
In Graph
's definition, you can constrain each associated type's associated type (!) to be equal to the corresponding associated type in Graph
.
pub trait Graph {
type Node: Node<Edge = Self::Edge>;
type Edge: Edge<Node = Self::Node>;
fn get_nodes(&self) -> Vec<Self::Node>;
}
这篇关于关联特征类型的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!