为什么下面的 Go 代码可以工作?
也就是说,由于 f
的类型和 b
是 interface{}
(而不是 bool
、int
或 string
中的任何一个),我怎么可能不强制转换或类型断言 f
?和 b
在三个中的每一个if
声明?
package main
import (
"fmt"
"reflect"
)
func foop(p map[string]interface{}) {
p["foo"] = true
}
func barp(p map[string]interface{}) {
p["bar"] = 17
}
func foop2(p map[string]interface{}) {
p["foo"] = "blah"
}
func main() {
p := make(map[string]interface{})
fmt.Printf("%v\n", p)
foop(p)
barp(p)
f := p["foo"]
b := p["bar"]
fmt.Printf("f: %T\n", f)
if f == true {
fmt.Println("ok")
}
fmt.Printf("b: %T\n", b)
if b == 17 {
fmt.Println("ok")
}
foop2(p)
f = p["foo"]
if f == "blah" {
fmt.Println("ok")
}
fmt.Printf("f: %T\n", f)
fmt.Printf("f: %s\n", reflect.TypeOf(f))
}
(去 Playground :https://play.golang.org/p/kPi25yW6tF)
最佳答案
与大多数 Go 语言问题一样,答案在 Go Programming Language Specification 中。 ,特别是关于 Comparison Operators 的部分.
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.
关于go - Go接口(interface){}与内置类型直接比较 : Why does this work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38251559/