我对Go编程语言相当不熟悉,我一直试图找到一种方法来将变量的类型作为字符串.到目前为止,我还没有找到任何有用的东西.我已经尝试使用typeof(variableName)获取变量的类型作为字符串,但这似乎没有效果.
Go是否有任何内置运算符可以获取变量的类型作为字符串,类似于JavaScript的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.
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*tle 13
package main
import "fmt"
import "reflect"
func main() {
num := 3
fmt.Println(reflect.TypeOf(num))
}
Run Code Online (Sandbox Code Playgroud)
这输出:
int
更新:您更新了问题,指定您希望类型为字符串. TypeOf返回一个Type,它有一个Name将类型作为字符串返回的方法.所以
typeStr := reflect.TypeOf(num).Name()
Run Code Online (Sandbox Code Playgroud)
更新2:更彻底,我要指出,你必须调用之间进行选择Name()或String()对你Type; 它们有时是不同的:
// Name returns the type's name within its package.
// It returns an empty string for unnamed types.
Name() string
Run Code Online (Sandbox Code Playgroud)
与:
// String returns a string representation of the type.
// The string representation may use shortened package names
// (e.g., base64 instead of "encoding/base64") and is not
// guaranteed to be unique among types. To test for equality,
// compare the Types directly.
String() string
Run Code Online (Sandbox Code Playgroud)