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
?
interface{} is the Go empty interface, a key concept. Every type implements it by definition. An interface is a type, so you can define for example: type Dog struct { Age interface{} }
To check if strings are equal in Go programming, use equal to operator == and provide the two strings as operands to this operator. If both the strings are equal, equal to operator returns true, otherwise the operator returns false.
Interface values Printf , you can use %v to print the concrete value and %T to print the dynamic type. The zero value of an interface type is nil, which is represented as [nil, nil] .
An interface value holds a value of a specific underlying concrete type. Calling a method on an interface value executes the method of the same name on its underlying type.
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
:
You can also try this playground https://play.golang.org/p/bgO1_V87v9k
In other words, handling equality seems easy in Go!
I am correcting my previous answer as I now believe it was wrong. When two interface values are compared the run-time will only panic if they are of the same type and it is non-comparable. If they contain different types then the result is false even if one or both types are non-comparable.
What are non-comparable types? Basically, they are slices, maps, functions and any struct or array type that uses them.
I have a summary of 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.reflect.DeepEqual(x, y any) bool
worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With