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

后端 未结 3 806
醉酒成梦
醉酒成梦 2021-02-11 23:32

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

3条回答
  •  无人及你
    2021-02-12 00:08

    There's no standard in Go language itself, yet (go 1.13).

    However, comparison utilities could provide their own way to support it.

    Function cmp.Equal (from google/go-cmp/cmp) supports definition of custom type comparator via definition of a Equal method:

    • If the values have an Equal method of the form "(T) Equal(T) bool" or "(T) Equal(I) bool" where T is assignable to I, then use the result of x.Equal(y)even if x or y is nil. Otherwise, no such method exists and evaluation proceeds to the next rule.

提交回复
热议问题