Go and interface{} equality

huangapple go评论87阅读模式
英文:

Go and interface{} equality

问题

我有以下代码:

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))
}

它的输出结果是:

true
true
false

我想知道为什么。在第一个情况中,可以看到将一个值包装在interface{}中并不会影响判断相等性,但是将一个空指针(等于nil)包装在interface{}中与interface{}(nil)不相同。为什么会这样呢?

英文:

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?

答案1

得分: 6

一个接口值封装了两个数据:(1) 类型和 (2) 该类型的值。关于比较,规范说明

> 接口值是可比较的。如果两个接口值具有相同的动态类型和相等的动态值,或者两个接口值都为 nil,则它们是相等的。

因此,接口值的两个数据部分都需要相等才能被视为相等。

在你的最后一个例子中,interface{}(a) 的动态类型是 *int,动态值为 nil,而 interface{}(nil) 的动态类型是 nil(即未设置类型),动态值也为 nil。由于类型不匹配,这两个值被认为是不相等的。

英文:

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.

huangapple
  • 本文由 发表于 2014年2月12日 13:32:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/21719484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定