英文:
interface & integer comparison in golang
问题
我不明白为什么第一个结果是false而第二个结果是true。
任何帮助将不胜感激。
func main() {
var i interface{}
i = uint64(0)
fmt.Println("[1] ", reflect.TypeOf(i), i == 0)
i = 0
fmt.Println("[2] ", reflect.TypeOf(i), i == 0)
var n uint64 = 32
fmt.Println("[3] ", reflect.TypeOf(n), n == 32)
}
// 结果
// [1] uint64 false
// [2] int true
// [3] uint64 true
在这里尝试 Go playground
英文:
I don't understand why the first result is false while second is true.
Any help will be appreciated.
func main() {
var i interface{}
i = uint64(0)
fmt.Println("[1] ", reflect.TypeOf(i), i == 0)
i = 0
fmt.Println("[2] ", reflect.TypeOf(i), i == 0)
var n uint64 = 32
fmt.Println("[3] ", reflect.TypeOf(n), n == 32)
}
// result
// [1] uint64 false
// [2] int true
// [3] uint64 true
Try it here Go playground
答案1
得分: 11
因为0是一个未指定类型的常量,默认类型是int,而不是uint64。当与接口进行比较时,你所比较的对象必须既是相同类型又是相同值才被认为是相等的。
参考链接:https://golang.org/ref/spec#Comparison_operators
等号操作符
==和!=适用于可比较的操作数。小于号<、小于等于号<=、大于号>和大于等于号>=适用于有序的操作数。这些术语和比较的结果定义如下:非接口类型X的值x和接口类型T的值t是可比较的,当X的值是可比较的并且X实现了T时。如果t的动态类型与X相同且t的动态值等于x,则它们是相等的。
英文:
Because 0 is an untyped constant whose default type is int, not uint64, and when doing comparison with an interface, the thing you are comparing to must be both the same type and the same value for them to be considered equal.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论