英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论