go - Go接口(interface){}与内置类型直接比较 : Why does this work?

标签 go types casting

为什么下面的 Go 代码可以工作?

也就是说,由于 f 的类型和 binterface{} (而不是 boolintstring 中的任何一个),我怎么可能强制转换或类型断言 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/

相关文章:

c# - 是否存在 `var` 可能导致问题的任何情况?

java - 具有类型转换的通用原始类型

java - 从文件读取列表时发生类转换异常

concurrency - 什么会导致代码阻塞?

MySQL:为什么使用 VARCHAR(20) 而不是 VARCHAR(255)?

c - 在 C 中,声明指针的正确语法是什么?

c++ - 在 C++ 中放松 void * 转换

com - 如何从 Go 进行 stdcall

javascript - 接收二维数组 args 作为 js.Value 并想要一个数组 ([]js.Value)

http - Golang 'http.NewRequest(method, url, body)' 无法创建正确格式的请求