Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude field when deriving PartialEq

Tags:

rust

Is there an easy way to annotate fields in a struct so that they are ignored when deriving the PartialEq trait? For example:

#[derive(PartialEq,Eq)]
pub struct UndirectedGraph {
    nodes: HashMap<NodeIdx, UndirectedNode>,
    // mapping of degree to nodes of that degree
    degree_index: Vec<HashSet<NodeIdx>>,
}

I want two undirected graphs to be considered equal when they have the same nodes field, but the degree_index field may differ (the vector may contain extra empty hash-sets at the end).

Obviously I could just implement the trait manually, but automatic derivation would be simpler.

like image 945
Henning Koehler Avatar asked Dec 07 '16 04:12

Henning Koehler


3 Answers

No, there is no way to do that currently and I doubt it will be supported.

You could consider making the fields that you want to compare into a sub-struct which is derived, which would make the implementation for the larger struct trivial.

like image 143
vitiral Avatar answered Oct 28 '22 04:10

vitiral


Check out the derivative create (docs). It provides alternate derive macros with more power than the standard library versions, including ways to ignore fields for Hash and PartialEq traits.

like image 37
dherman Avatar answered Oct 28 '22 02:10

dherman


I would also recommend the derivative crate if you need a more sophisticated form of #[derive].

If you only need something like this once or twice, it may be easier to just implement the required traits manually rather than derive them. PartialEq and Eq are very easy to implement yourself:

impl PartialEq for UndirectedGraph {
    fn eq(&self, other: &Self) -> bool {
        self.nodes == other.nodes
    }
}
impl Eq for UndirectedGraph {}
like image 2
Eric Seppanen Avatar answered Oct 28 '22 02:10

Eric Seppanen