go - 类型开关不检测 float32

标签 go

package main

import "fmt"

func main() {
    printType(4.0)
}

func printType(i interface{}) {
    switch i := i.(type) {
    case float32:
        fmt.Println("This is a float type", i)
    }
}

出于某种原因,此代码未将 4.0 值检测为 float32,但将其检测为 float64 - 这是为什么呢?我在 win x64 机器上运行它。

最佳答案

For some reason this code does not detect 4.0 value as float32 but it detects it as float64 - why is that?

因为 float64default type对于无类型浮点常量。相关部分强调:

An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required, for instance, in a short variable declaration such as i := 0 where there is no explicit type. The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.

关于go - 类型开关不检测 float32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54045074/

相关文章:

go - rune 与字符串范围内的字节

vue.js - 如何同时使用 Vue-Router 和 Gorilla Mux 路由器

go - Gin 上的 router.Static() 和 router.Use(static.Serve()) 有什么区别?

generics - 如何获取 map 的key

rest - 在 REST 上不支持的 HTTP 方法返回什么响应代码?

go - 连接在goroutine中关闭

go - 检查主机是否可以在特定网络接口(interface)上访问

unit-testing - 在 Go 中测试内部结构

go - 在 GoLang 中将字符串转换为 func 类型

function - Go 的 struct 方法在调用中抛出太多参数