简体   繁体   English

将Go接口{}直接比较为内置类型:为什么这样做?

[英]Direct comparison of Go interface{} to built-in types: Why does this work?

Why does the following Go code work? 为什么以下Go代码有效?

That is, since the types of f and b are interface{} (and not any of bool , int or string ), how is it possible for me to get away with not casting or type-asserting f and b in each of the three if statements? 也就是说,由于fb的类型是interface{} (而不是boolintstring任何一个),我怎么可能在三者中的每一个中都没有强制转换或类型断言fb 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))
}

(Go Playground: https://play.golang.org/p/kPi25yW6tF ) (去游乐场: https//play.golang.org/p/kPi25yW6tF

As with most Go language questions, the answer is in the Go Programming Language Specification , specifically the section on Comparison Operators . 与大多数Go语言问题一样,答案在Go编程语言规范中 ,特别是有关比较运算符的部分。

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. 当类型X的值可比较且X实现T时,非接口类型X的值x和接口类型T的值t是可比较的。如果t的动态类型与X相同并且t的动态值等于x,则它们相等。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM