The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
kidlj

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

  •  
  •   kidlj ·
    kidlj · Apr 2, 2019 · 3691 views
    This topic created in 2772 days ago, the information mentioned may be changed or developed.
    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 replies  •  2019-04-03 09:41:50 +08:00
    takeoffyoung
    takeoffyoung
    Apr 2, 2019❤️1
    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
    kidlj
    OP
    Apr 2, 2019
    2
    @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
    reus
    Apr 2, 2019❤️1
    3
    @kidlj 看 Conversions 一节: https://golang.org/ref/spec#Conversions

    x is assignable to T.

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

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

    >> 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
    kidlj
    OP
    Apr 3, 2019
    6
    @ggicci 哈哈哈感谢哦。我睁这么大眼睛竟然没看见这一行!好粗心。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4283 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:09 · PVG 09:09 · LAX 17:09 · JFK 20:09
    ♥ Do have faith in what you're doing.