BadCoder
BadCoder

Reputation: 141

Is it possible to match structs to compare them?

Similar to How to match struct fields in Rust?, is it possible to match a struct like Default without physically writing out the fields? I do not want to write out the fields constantly.

Something along the lines of:

let someValue = Struct { /* ... */ };
match someValue {
    Struct::default() => println!("Default!"),
    _ => println!("Not Default"),
}

This gives an error.

I did some testing on the Rust Playground but I only ended up running into the problem of matching named variables described in the docs.

What is your best solution to comparing many structs? Is it using #[derive(PartialEq)] and if statements?

Upvotes: 0

Views: 1687

Answers (2)

Kaplan
Kaplan

Reputation: 3718

If you can use #[derive(Ord, Eq, PartialOrd, PartialEq)] on Struct this variant is possible:

use std::cmp::Ordering;

match some_value.cmp(&Struct::default()) {
    Ordering::Equal => println!("Default!"),
    _               => println!("Not Default"),
}    

Upvotes: 0

Kornel
Kornel

Reputation: 100080

Rust's patterns aren't values to compare to. They're more related to variable assignment (destructuring).

There is a "match guard" syntax that can be used:

match some_value {
   tmp if tmp == Struct::default() => /* it's default-like-ish */
}

Upvotes: 1

Related Questions