如何获取类型的字符串表示形式? [英] How to get the string representation of a type?

查看:178
本文介绍了如何获取类型的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了以下类型:

 类型ID uuid.UUID 


如何以编程方式将字符串作为字符串获取,以便以后重构可能比以下方式容易:

  fmt.Sprintf(%T,ID {})

我不太喜欢它,因为它实例化了它,也来自于一个接口。

解决方案

您可以使用软件包 reflect (< a href =https://golang.org/pkg/fmt/ =nofollow noreferrer> fmt 软件包也是如此) 。您可以从指针开始指向该类型,并使用键入的 nil 指针值,而无需分配,您可以从其 reflect.Type 导航描述符指向使用 Type.Elem()的指针的 base 类型(或元素类型)的描述符。



例子:

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

输出(在去游乐场试试) :

  ID 


$ b注意:注意 Type.Name()可能返回一个空的字符串(如果 Type 代表一个未命名的类型)。如果您使用类型声明(使用类型 code> keyword),那么你已经命名了类型,所以 Type.Name()将返回一个非空的类型名称。但是,对于 * [] string 类型的变量,使用上面的代码会给你一个空字符串:

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

输出(在 Go Playground ):

 <$ c $ 




$ b

查看相关问题:

$ b

Golang反映:从名称获取类型表示形式



使用反射识别非内建类型


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.

解决方案

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

这篇关于如何获取类型的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆