我应该如何减少 Rust 类型签名的重复? [英] How should I reduce repetition in rust type signatures?

查看:51
本文介绍了我应该如何减少 Rust 类型签名的重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下不是很干的工作代码:

I have the following working code that isn't very DRY:

impl<'a, G, E, N, EW, NW, ER, NOW, EOW> Overlay<'a, G, E, N, EW, NW, ER, NOW, EOW>
where
    &'a G: GraphBase<EdgeId = E, NodeId = N> +
           Data<EdgeWeight = EW, NodeWeight = NW> +
           DataMap,
    ER: EdgeRef<Weight = EW, EdgeId = E, NodeId = N>,
    E: Copy + Eq + Hash,
    N: Copy + Eq + Hash,
{
    fn overlayed_elements(&'a self) -> OverlayedItems<'a, G, E, N, EW, NW, ER, NOW, EOW>{
        OverlayedItems{
            overlay: self,
            phase: Phase::Nodes(self.nodes.iter()),
            node_indexes: HashMap::new(),
        }
    }
    pub fn overlay_edge<'b>(&'b mut self, edge: ER, eow: EOW) {
        self.edges.insert(edge.id(), eow);
        self.edge_refs.insert(edge.id(), edge);
    }
    pub fn overlay_node<'b>(&'b mut self, node: N, now: NOW) {
        self.nodes.insert(node, now);
    }
    fn remove_edge<'b>(&'b mut self, edge: E) {
        self.edges.remove(&edge);
        self.edge_refs.remove(&edge);
    }
    fn remove_node<'b>(&'b mut self, node: N) {
        self.nodes.remove(&node);
    }
}

上下文

游乐场

我有很多重复的<'a, G, E, N, EW, NW, ER, NOW, EOW> 并且通常似乎所有这些特质thingamamagigs都在使用很多空间.这只是糟糕的代码,还是我做错了什么?

I have a lot of repetition of <'a, G, E, N, EW, NW, ER, NOW, EOW> and it generally seems that all these trait thingamagigs are taking up a lot of space. Is this just bad code, or am I doing something wrong?

推荐答案

关联类型并不总是需要有自己的类型参数.例如,您可以在绑定中编写 G::EdgeId 而不是具有单独的参数 E.

Associated types do not always need to have their own type parameters. For example, you can write G::EdgeId in a bound instead of having a separate parameter E.

我调整了操场链接中的代码以减少类型参数的数量.这是更新链接例如,Overlay 现在有 4 个而不是 8 个类型参数:

I adjusted the code in the playground link to reduce the number of type arguments. Here's the updated link. For example, Overlay now has 4 instead of 8 type arguments:

pub struct Overlay<G, ER, NOW, EOW>
where
    G: GraphBase + Data,
    ER: EdgeRef<Weight = G::EdgeWeight, EdgeId = G::EdgeId, NodeId = G::NodeId>,
{
    nodes: HashMap<G::NodeId, NOW>,
    edges: HashMap<G::EdgeId, EOW>,
    edge_refs: HashMap<G::EdgeId, ER>,
    graph: G,
}

请注意,我删除了 G::NodeIdG::EdgeId 的(不必要的)Copy + Eq + Hash 特征边界.此外,G 不再落后于特征边界中的引用,这可能会导致生命周期问题,但如果需要,可以修复这些问题.

Note that I removed the (unnecessary) Copy + Eq + Hash trait bounds for G::NodeId and G::EdgeId. Also, G is no longer behind a reference in the trait bounds, which might cause lifetime issues, but these can be fixed if necessary.

这篇关于我应该如何减少 Rust 类型签名的重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆