V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
kidlj
V2EX  ›  Go 编程语言

Golang interface value 可以和具体类型 value 直接比较?

  •  
  •   kidlj ·
    kidlj · 2019-04-02 16:20:29 +08:00 · 2721 次点击
    这是一个创建于 1849 天前的主题,其中的信息可能已经有所发展或是发生改变。
    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	var s = "hello world"
    	var x interface{} = s
    	if x == s {
    		fmt.Println("good")
    	} else {
    		fmt.Println("bad")
    	}
    }
    

    https://play.golang.org/p/PzEapDah_V4

    一直以为只有两个都是 interface value 才能互相比较,原来 interface value 也可以和具体类型的 value 直接比较。但是在 golang spec 文档里没找到关于这一点的说明。

    https://golang.org/ref/spec#Comparison_operators

    6 条回复    2019-04-03 09:41:50 +08:00
    takeoffyoung
        1
    takeoffyoung  
       2019-04-02 16:33:11 +08:00   ❤️ 1
    第一行不是说了嘛,能赋值即可。
    In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.

    再者,interface 类型不是 concrete type,而是 static type,运行时不会关心 static type。
    kidlj
        2
    kidlj  
    OP
       2019-04-02 16:37:34 +08:00
    @kidlj 第一行说的是一个前提条件啊,后面的列表才是可比较项的具体定义。那里只列出了 interface value 比较的规则,没有列出 interface value 和 concrete type value 的比较规则:

    - 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.
    reus
        3
    reus  
       2019-04-02 16:59:09 +08:00   ❤️ 1
    @kidlj 看 Conversions 一节: https://golang.org/ref/spec#Conversions

    x is assignable to T.

    这样编译器就可以将其中一个操作数做隐式转换,这样就相当于做同样类型的比较,所以不需要特别说吧。
    kidlj
        4
    kidlj  
    OP
       2019-04-02 17:16:37 +08:00
    @reus 嗯,理解了。这个时候就跟向 interface value 赋值一样,进行了隐士转换,具体类型值变成了接口类型值。

    这样一来,就是比较两个 interface value 的问题了,确实没必要在 comparison operators spec 文档里对上述的这种情况进行特别说明。
    ggicci
        5
    ggicci  
       2019-04-03 00:23:20 +08:00   ❤️ 1
    明明是这行:

    >> 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.
    kidlj
        6
    kidlj  
    OP
       2019-04-03 09:41:50 +08:00
    @ggicci 哈哈哈感谢哦。我睁这么大眼睛竟然没看见这一行!好粗心。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1548 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:59 · PVG 07:59 · LAX 16:59 · JFK 19:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.