【问题标题】:Constraints on associated trait types对相关特征类型的限制
【发布时间】:2019-02-07 04:04:33
【问题描述】:

这是一个(有点做作的)示例来说明我想做的事情

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 相同类型?

我记得读过一些关于允许对这类事情进行更丰富约束的功能(当时未实现)的内容,但我不记得它的名称,也找不到它。

【问题讨论】:

    标签: rust associated-types


    【解决方案1】:

    Graph 的定义中,您可以将每个关联类型的关联类型(!)限制为等于Graph 中对应的关联类型。

    pub trait Graph {
        type Node: Node<Edge = Self::Edge>;
        type Edge: Edge<Node = Self::Node>;
        fn get_nodes(&self) -> Vec<Self::Node>;
    }
    

    【讨论】:

    • 我最初认为这行不通,因为特征没有类型参数,但它确实有!谢谢!
    • 关联类型是排序的类型参数
    猜你喜欢
    • 2015-09-23
    • 2011-11-19
    • 2018-03-11
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多