[英]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
trait中表示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>;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.