Mediocre Gopher
Mediocre Gopher

Reputation: 2304

Go and interface{} equality

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?

Upvotes: 6

Views: 2233

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

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.

Upvotes: 7

Related Questions