假设我定义了以下类型:
类型ID uuid.UUID 如何以编程方式将字符串作为字符串获取,以便以后重构可能比以下方式容易: fmt.Sprintf(%T,ID {})我不太喜欢它,因为它实例化了它,也来自于一个接口。
解决方案您可以使用软件包 reflect ( 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 类型的变量,使用上面的代码会给你一个空字符串:
输出(在 Go Playground ): <$ c $ $ b查看相关问题: Golang反映:从名称获取类型表示形式
使用反射识别非内建类型
Let's say I have the following type defined:
type ID uuid.UUIDHow 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):
IDNote: 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
更多推荐
如何获取类型的字符串表示形式?
发布评论