Go 比较浮点值和常量

Go 比较浮点值和常量,go,floating-point,comparison,constants,Go,Floating Point,Comparison,Constants,在使用接口{}和它的类型检测时,我发现了一个不清楚的和有点奇怪的东西,与JSON的未签名值相比。 包干管 import ( "fmt" "os" "encoding/json" "reflect" ) type Message struct { Code int `json:"code"` } func main() { var jsons []byte = []byte(`{ "code":200 }`) var t = make(m

在使用接口{}和它的类型检测时,我发现了一个不清楚的和有点奇怪的东西,与JSON的未签名值相比。 包干管

import (
    "fmt"
    "os"
    "encoding/json"
    "reflect"
)

type Message struct {
    Code int `json:"code"`
}

func main() {
    var jsons []byte = []byte(`{ "code":200 }`)
    var t = make(map[string]interface{})
    e:= json.Unmarshal(jsons, &t)
    if e != nil {
        fmt.Printf("Unmarshal error: %v", e)
        os.Exit(1)
    }

    var c float64 = 200
    fmt.Printf("Comparison with manually defined float64: %t\n",c == 200) /// comparison with float64 is ok

    fmt.Printf("Type of 'code' value: %s\n", reflect.TypeOf(t["code"])) // here is a float64 type
    fmt.Printf("Comparison without type assertion: %t\n", t["code"] == 200) // returning false
    fmt.Printf("Comparison with type assertion: %t\n", t["code"].(float64) == 200) // returning true

    fmt.Printf("\n%", t["code"])
    fmt.Printf("\n%", t["code"].(float64))
    }
输出:

Comparison with manually defined float64: true
Type of 'code' value: float64
Comparison without type assertion: false
Comparison with type assertion: true

%!(NOVERB)%!(EXTRA float64=200)
%!(NOVERB)%!(EXTRA float64=200)
如您所见,这两个变量看起来相同,具有相同的类型和值,但比较的结果不同

有人能帮我理解为什么吗


这是一个操场-

200
是一个非类型常量。委员会:

非类型化常量有一个默认类型,该类型是在需要类型化值的上下文中(例如,在没有显式类型的短变量声明中,如i:=0)将常量隐式转换为的类型。非类型化常量的默认类型分别为bool、rune、int、float64、complex128或string,具体取决于它是布尔、rune、整数、浮点、复数还是string常量

表达式
t[“code”]==200
的计算结果为false,因为非类型化的
200
隐式转换为默认的
int
,以便与
接口{}
进行比较。
接口{}
中的
float64
不等于
int
200

其他比较返回true,因为不需要将隐式类型转换为默认类型

表达式
t[“code”]==200.0
的计算结果为true,因为
200.0
是一个
float64
常量

比较结果与JSON解码无关。看