英文:
How to get the string representation of a type?
问题
让我们假设我有以下定义的类型:
type ID uuid.UUID
如何以编程方式将该类型获取为字符串,以便以后容易进行重构,而不仅仅是使用:
fmt.Sprintf("%T", ID{})
我不太喜欢这种方式,因为它会实例化它,而且还是通过接口。
英文:
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
得分: 4
你可以使用reflect
包(fmt
包在底层也是这样做的)。你可以从类型的指针开始,并使用一个已分配的、类型化的nil
指针值,然后可以通过其reflect.Type
描述符导航到指针的基本类型(或元素类型)的描述符,使用Type.Elem()
。
示例:
t := reflect.TypeOf((*ID)(nil)).Elem()
name := t.Name()
fmt.Println(name)
输出(在Go Playground上尝试):
ID
注意:要注意Type.Name()
可能返回一个空的字符串(如果Type
表示一个无名类型)。如果你使用的是类型声明(使用type
关键字),那么你已经给类型命名了,所以Type.Name()
将返回一个非空的类型名称。但是,如果你使用上面的代码来处理类型为*[]string
的变量,将会得到一个空字符串:
var s *[]string
t := reflect.TypeOf(s).Elem()
name := t.Name()
fmt.Printf("%q", name)
输出(在Go Playground上尝试):
""
相关问题请参考:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论