【发布时间】: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) }