Skip to content

Add struct_eq builtin for member-wise struct comparisons#2801

Open
NotsoanoNimus wants to merge 4 commits intoc3lang:masterfrom
NotsoanoNimus:dev/struct_cmp_macro
Open

Add struct_eq builtin for member-wise struct comparisons#2801
NotsoanoNimus wants to merge 4 commits intoc3lang:masterfrom
NotsoanoNimus:dev/struct_cmp_macro

Conversation

@NotsoanoNimus
Copy link
Contributor

Allows comparisons of input structures that don't already have an == overload (and it will just compare them anyway if they do). This reduces the need to define @operator(==) overrides which just do return self.a == self.a && self.b == self.b && ...;. They can now become something like this:

struct MyType
{
    bool has_field;
    uint128 something;
    String[] list;
}
// This...
fn bool MyType.old_eq(&self, MyType other) @operator(==)
{
    return self.has_field == other.has_field && self.something == other.something && self.list[..] == other.list[..];
}
// ... now becomes:
fn bool MyType.eq(&self, MyType other) @operator(==) => struct_eq(*self, other);

This is especially useful when memcmp-style comparisons of structs are not.

You can also use the variadic arguments list to supply strings in dot-notation to exclude certain fields from being compared. See the unit tests for more information about how to do this.

The implementation is a bit redundant because there are no flow-control statements at compile-time. This could certainly use a few extra reviewers to ensure it works as broadly as possible, but tests seem to show a good coverage/capability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant