我有以下代码:
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/