如何获取类型的字符串表示形式? [英] How to get the string representation of a type?
问题描述
假设我定义了以下类型:
类型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
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
(thefmt
package does that too under the hood). You may start from the pointer to the type, and use a typednil
pointer value without allocation, and you can navigate from itsreflect.Type
descriptor to the descriptor of the base type (or element type) of the pointer usingType.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 emptystring
(if theType
represents an unnamed type). If you're using a type declaration (with thetype
keyword), then you already named the type, soType.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屋!