【问题标题】:How to get the string representation of a type?如何获取类型的字符串表示?
【发布时间】:2017-06-13 19:10:40
【问题描述】:

假设我定义了以下类型:

type ID uuid.UUID

如何以编程方式将类型作为字符串获取,以便以后重构而不是可能:

fmt.Sprintf("%T", ID{})

我不太喜欢,因为它实例化了它,也是从一个接口。

【问题讨论】:

    标签: go reflection types


    【解决方案1】:

    您可以使用包reflectfmt 包也可以在后台执行此操作)。您可以从 pointer 指向类型,并使用 typed nil 指针值而无需分配,您可以从其 reflect.Type 描述符导航到使用Type.Elem()的指针的base类型(或element类型)。

    例子:

    t := reflect.TypeOf((*ID)(nil)).Elem()
    name := t.Name()
    fmt.Println(name)
    

    输出(在Go Playground上试试):

    ID
    

    注意:注意Type.Name() 可能返回一个空的string(如果Type 代表一个未命名的类型)。如果您使用的是type declaration(带有type 关键字),那么您已经命名了该类型,因此Type.Name() 将返回一个非空类型名称。但是例如将上面的代码用于*[]string 类型的变量会给你一个空字符串:

    var s *[]string
    t := reflect.TypeOf(s).Elem()
    name := t.Name()
    fmt.Printf("%q", name)
    

    输出(在Go Playground 上试试):

    ""
    

    查看相关问题:

    Golang reflect: Get Type representation from name?

    Identify non builtin-types using reflect

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      相关资源
      最近更新 更多