繁体   English   中英

对相关特质类型的约束

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM