Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go and interface{} equality

Tags:

interface

go

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?

like image 787
Mediocre Gopher Avatar asked Feb 12 '14 05:02

Mediocre Gopher


People also ask

What is interface {} Go?

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.

How do you check for equality of two 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.

How do you check for equality in Go?

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.

What is Go interface value?

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.


1 Answers

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.

like image 83
James Henstridge Avatar answered Oct 11 '22 22:10

James Henstridge