interface - Go 和 interface{} 相等

标签 interface go

我有以下代码:

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 指针(等于 nil) 包装在 interface{} 中与 interface{}(nil) 不同。这是为什么?

最佳答案

接口(interface)值包含两部分数据:(1) 类型和 (2) 该类型的值。关于比较,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.

因此,为了使接口(interface)值被视为相等,两条数据都需要相等。

在您的最后一个示例中,interface{}(a) 具有动态类型 *int 和动态值 nil,而interface{}(nil) 具有动态类型 nil(即未设置类型)和动态值 nil。由于类型不匹配,因此认为这两个值不相等。

关于interface - Go 和 interface{} 相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21719484/

相关文章:

c# - 触发一个事件而不订阅它

c# - 无法将 .Net ConcurrentDictionary<K,V> 转换为 IReadOnlyDictionary<K,V> 接口(interface)?

variables - Go中这个括号括起来的变量声明语法是什么?

sql - 戈朗 pq : syntax error when executing sql

c# - 界面中发生了什么?

typescript - instanceof 检查接口(interface)

c# - 在参数 C# 中传递接口(interface)

go - big.Float SetPrec 奇怪的行为

string - 如何在 Go 中生成固定长度的随机字符串?

go - 将 JSON 公钥/私钥对转换为 rsa.PrivateKey 和 rsa.PublicKey