Idiomatic way to deal with many types of structs?

I wrote up an example on Rust Playground where I am trying to handle more than 1 struct in a single function. I want to write a method called isDefault() which would essentially check if any struct I pass in is equal to its default case.

The code for the function:

fn isDefault(foo: Structs) -> bool {
    match foo {
        Structs::MyStruct(MyStruct) => {
            if MyStruct == MyStruct::default() { return true; }
            else { return false; }
        },
        Structs::MyStruct2(MyStruct2) => {
            if MyStruct2 == MyStruct2::default() { return true; }
            else { return false; }
        },
    }
}

However, I feel like I am writing redundant code. I know that this function would not be the only time I try to do something similar. I dream of having something like this:

fn isDefault(foo: Structs) -> bool {
    if (foo's value) == (foo's type)::default() { return true; }
    else { return false; }
}

I was reading up on traits and inheritance and was wondering if that would be a better long term solution. I can't seem to find the solution I am looking for online and I am sure it is because I am bad at wording my questions.

How should I go about this?

Use a generic type with the trait bounds necessary for both constructing a default value, and comparing equality. E.g. like this.

1 Like

In a sense, it does! This is called a trait bound. It means that the function can only be called for types that implement both Default and PartialEq traits. Both traits are required because methods from both are called on the input.

You can read more about traits and generics in chapter 10 in The Book. Specifically, there is a section in 10.2 that describes the + syntax and where clauses.

1 Like

I apologize I deleted my post because I wasn't sure if I replied properly. The original question for anyone else who reads it was " That's extremely clean, does the line where T: Default + PartialEq, check if the value has both a Default and PartialEq?".

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.