Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define equality for named types/structs?

After reading a related question about using slices in maps, I became curious about equality in Go.

I know it's possible to override the equals method of a Java Object. Is there a similar way to define how Go checks user defined types/structs for equality? If so, there would be a workaround for the issue referenced above. I thought using interface{} values might offer a solution but I received the error message panic: runtime error: hash of unhashable type []int.

like image 644
Bill DeRose Avatar asked Dec 01 '13 07:12

Bill DeRose


People also ask

Can you compare structs in Golang?

In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method.

What is the difference between equals () and == in C#?

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.

What is equality in C#?

Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward. You can use the == operator, as shown in the following example. C# Copy. int a = GetOriginalValue(); int b = GetCurrentValue(); // Test for value equality.

Which of the following interface can be used to provide custom equality logic?

IEquatable<T> interface by providing a type-specific Equals method.


1 Answers

No. You can't modify the equality operator and there is no built-in way to add support for custom types to use == syntax. Instead you should compare the pointer values using reflect.DeepEqual.

Go supports equality checking structs.

type Person struct {     Name string }  a := Person{"Bill DeRose"} b := Person{"Bill DeRose"}  a == b // true 

It won't work with pointer fields (in the way you want) because the pointer addresses are different.

type Person struct {     Friend *Person }  a := Person{Friend: &Person{}} b := Person{Friend: &Person{}}  a == b // false   import "reflect"  a := Person{Friend: &Person{}} b := Person{Friend: &Person{}}  reflect.DeepEqual(a, b) // true 

Keep in mind there are caveats.

In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value.

like image 131
AJcodez Avatar answered Oct 05 '22 12:10

AJcodez