'Checking equality of interface{}

I am searching a []interface{} slice for a given interface{} value:

var v interface{}
for i := 0; i < len(A); i++ {
  if (A[i] == v) {
    fmt.Println("Gotcha!")
    break
  }
}

In the trivial case the types are int. However what should I do if, for example, the types are some custom struct?



Solution 1:[1]

Thanks to @CodingPickle comment, I provide the following from the Go Programming Language Specification

The equality operators == and != apply to operands that are comparable.

Regarding interface{}s and structs:

  • Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
  • A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x.
  • Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

You can also try this playground https://play.golang.org/p/bgO1_V87v9k

In other words, handling equality seems easy in Go!

Solution 2:[2]

Update: since the above question and answers were written the Go language has changed slightly.

Previously if two interfaces are compared and either or both contained a non-comparable type then the run-time would panic. Now the runtime will only panic if they both contain the same non-comparable type. (If they contain different types then the result is now false even if either type is non-comparable.)

What are non-comparable types? Basically, they are slices, maps, functions and any struct or array type that uses them.

AFAIK this was a silent change around Go 1.9 or 1.10.

Solution 3:[3]

I have a summary of properties of Go types

properties of Go types

Explanation

  • depends - it's only allowed if the contained type(s) are comparable.) For Interface types the code will compile but if at runtime the types contained are not comparable then the runtime will panic. Thanks to @Andrew W. Phillips.

Solution 4:[4]

reflect.DeepEqual(x, y any) bool

worked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mh-cbon
Solution 2 Andrew W. Phillips
Solution 3
Solution 4 Ken