I have the following code:
package main
import "fmt"
func main() {
fmt.Println(interface{}(1) == interface{}(1))
var a *int
fmt.Println(a == nil)
fmt.Println(interface{}(a) == interface{}(nil))
}
and it outputs:
true
true
false
I'm wondering why. In the first case it can be seen that wrapping a value in an interface{}
doesn't stop equality from being determined, and yet a nil pointer (which is equal to nil
) wrapped in an interface{}
is not the same as interface{}(nil)
. Why is this?
In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface.
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.
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.
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.
An interface value packages up two pieces of data: (1) a type and (2) a value of that type. On the subject of comparison, the spec says:
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.
So both pieces of data need to be equal for the interface values to be considered equal.
In your final example, interface{}(a)
has a dynamic type of *int
and a dynamic value of nil
, while interface{}(nil)
has a dynamic type of nil
(i.e. no type set) and a dynamic value of nil
. Since the types do not match, the two values are not considered equal.
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