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

2019-04-02 16:20:29 +08:00
 kidlj
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

2727 次点击
所在节点    Go 编程语言
6 条回复
takeoffyoung
2019-04-02 16:33:11 +08:00
第一行不是说了嘛,能赋值即可。
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
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
2019-04-02 16:59:09 +08:00
@kidlj 看 Conversions 一节: https://golang.org/ref/spec#Conversions

x is assignable to T.

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

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

>> 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
2019-04-03 09:41:50 +08:00
@ggicci 哈哈哈感谢哦。我睁这么大眼睛竟然没看见这一行!好粗心。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/551294

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX