加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang中的接口和整数比较

发布时间:2020-12-16 19:22:21 所属栏目:大数据 来源:网络整理
导读:我不明白为什么第一个结果是假的,而第二个结果是真的. 任何帮助将不胜感激. 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
我不明白为什么第一个结果是假的,而第二个结果是真的.

任何帮助将不胜感激.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读