【问题标题】:How to find if type is float64 [closed]如何查找类型是否为 float64 [关闭]
【发布时间】:2019-12-21 03:51:06
【问题描述】:

我正在尝试查找变量是否为 float64 类型:

package main
import ("fmt")
func main() {
    myvar := 12.34
    if myvar.(type) == float64 { 
        fmt.Println("Type is float64.")
    }
}

但是,它不起作用并给出以下错误:

./rnFindType.go:6:10: use of .(type) outside type switch
./rnFindType.go:6:21: type float64 is not an expression

问题是什么,如何解决?

【问题讨论】:

  • Go 是一种静态类型语言,在您的示例中,它不能是 float64 以外的其他类型(这是您的短变量声明中使用的浮点常量 12.34 的默认类型)。如果该值是接口类型,那么您可以使用 type assertion,它看起来像这样:if x, ok := myvar.(float64); ok { fmt.Println("its float64:", x) }

标签: go types


【解决方案1】:

您知道myvarfloat64,因为变量是用具体类型float64 声明的。

如果myvar 是接口类型,那么您可以使用type assertion 来确定具体值是否是某种类型。

var myvar interface{} = 12.34
if _, ok := myvar.(float64); ok {
    fmt.Println("Type is float64.")
}

https://play.golang.org/p/n5ftbp5V2Sx试试这个程序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多