首页 文章

在Go编程语言中,是否可以将变量的类型作为字符串获取?

提问于
浏览
6

我一直试图找到一种方法来将变量的类型作为字符串 . 到目前为止,我还没有尝试使用 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 回答

  • 12

    reflect包中有TypeOf函数:

    package main
    
    import "fmt"
    import "reflect"
    
    func main() {
        num := 3
        fmt.Println(reflect.TypeOf(num))
    }
    

    这输出:

    int
    

    Update: 您更新了问题,指定您希望类型为字符串 . TypeOf 返回 Type ,它有一个 Name 方法,该类型返回字符串类型 . 所以

    typeStr := reflect.TypeOf(num).Name()
    

    Update 2: 为了更加彻底,我应该指出,你可以在 Type 上调用 Name()String() 之间做出选择;它们有时是不同的:

    // Name returns the type's name within its package.
    // It returns an empty string for unnamed types.
    Name() string
    

    与:

    // 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
    
  • 14

    如果您只想打印该类型: fmt.Printf("%T", num) 将起作用 . http://play.golang.org/p/vRC2aahE2m

相关问题