Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare Tuples in Rust

I’m writing a test case for a function which returns a tuple including an enum. I want to verify that the returned tuple matches what I am expecting.

How I do compare tuples composed of enums in Rust? The following fails to compile:

enum Test {
  Foo,
  Bar
}
assert_eq!((1, Test::Foo), (1, Test::Foo));

(Of course, one of those tuples is generated at runtime by a method.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Tuples already implement PartialEq and Debug if all their elements do, but you’re missing both a Debug and PartialEq implementation for your custom enum:

#[derive(Debug, PartialEq)]
enum Test {
  Foo,
  Bar
}

With that your expected assert_eq!((1, Test::Foo), (1, Test::Foo)); works.

If you can’t implement either trait you can use matches!(<value>, <pattern>):

let got = (1, Test::Foo); // calculate your result
assert!(matches!(got, (1, Test::Foo)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading