前端之家收集整理的这篇文章主要介绍了
golang中的接口和整数比较,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
502_0@
我不明白为什么第一个结果是假的,而第二个结果是真的.
任何帮助将不胜感激.
func main() {
var i interface{}
i = uint64(0)
fmt.Println("[1] ",reflect.TypeOf(i),i == 0)
i = 0
fmt.Println("[2] ",i == 0)
var n uint64 = 32
fmt.Println("[3] ",reflect.TypeOf(n),n == 32)
}
// result
// [1] uint64 false
// [2] int true
// [3] uint64 true
在这里尝试Go playground
因为0是一个非类型化常量,其默认类型是int,而不是uint64,并且在与接口进行比较时,您要比较的东西必须是相同的类型,并且它们被视为相同的相同值.
https://golang.org/ref/spec#Comparison_operators
The equality operators == and != apply to operands that are comparable. The ordering operators <,<=,>,and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:
A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t’s dynamic type is identical to X and t’s dynamic value is equal to x.