我一直试图找到一种方法来将变量的类型作为字符串 . 到目前为止,我还没有尝试使用 typeof(variableName)
来获取变量's type as a string, but this doesn' t似乎是有效的 .
Go是否有任何内置运算符可以获取变量's type as a string, similar to JavaScript' s typeof
运算符或Python的 type
运算符?
//Trying to print a variable's type as a string:
package main
import "fmt"
func main() {
num := 3
fmt.Println(typeof(num))
//I expected this to print "int", but typeof appears to be an invalid function name.
}
2 回答
reflect包中有TypeOf函数:
这输出:
Update: 您更新了问题,指定您希望类型为字符串 .
TypeOf
返回Type
,它有一个Name
方法,该类型返回字符串类型 . 所以Update 2: 为了更加彻底,我应该指出,你可以在
Type
上调用Name()
或String()
之间做出选择;它们有时是不同的:与:
如果您只想打印该类型:
fmt.Printf("%T", num)
将起作用 . http://play.golang.org/p/vRC2aahE2m