douwuying4709 2017-01-28 00:42
浏览 33
已采纳

如何获取类型的字符串表示形式?

Let's say I have the following type defined:

type ID uuid.UUID

How would I get the type as string in a programmatic way so it's easy to refactor later other than maybe:

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

which I don't quite like because it instantiates it, also from an Interface.

  • 写回答

1条回答 默认 最新

  • douyun6399 2017-01-28 01:44
    关注

    You may use package reflect (the fmt package does that too under the hood). You may start from the pointer to the type, and use a typed nil pointer value without allocation, and you can navigate from its reflect.Type descriptor to the descriptor of the base type (or element type) of the pointer using Type.Elem().

    Example:

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

    Output (try it on the Go Playground):

    ID
    

    Note: be aware that Type.Name() may return an empty string (if the Type represents an unnamed type). If you're using a type declaration (with the type keyword), then you already named the type, so Type.Name() will return a non-empty type name. But using the above code for a variable of type *[]string for example will give you an empty string:

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

    Output (try it on the Go Playground):

    ""
    

    See related questions:

    Golang reflect: Get Type representation from name?

    Identify non builtin-types using reflect

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口