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

huangapple go评论71阅读模式
英文:

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上尝试):

""

相关问题请参考:

https://stackoverflow.com/questions/40879748/golang-reflect-get-type-representation-from-name/40882963#40882963

https://stackoverflow.com/questions/36310538/identify-non-builtin-types-using-reflect/37292523#37292523

英文:

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:

https://stackoverflow.com/questions/40879748/golang-reflect-get-type-representation-from-name/40882963#40882963

https://stackoverflow.com/questions/36310538/identify-non-builtin-types-using-reflect/37292523#37292523

huangapple
  • 本文由 发表于 2017年1月28日 08:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/41905222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定