打印结构的类型而不创建其实例。

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

Print type of a structure without creating its instance

问题

在Go语言中,我可以通过fmt.Printf("%T", Struct{})来打印一个结构体的类型,但是这样会创建一个新的结构体实例,从而占用内存。所以我可以只打印fmt.Printf("main.Struct"),但是假设有人重构了Struct的名称,那么打印语句就不会更新,代码就会出错。

如何在不创建结构体实例的情况下打印结构体的类型?

英文:

In Go, I can print a type of a structure by fmt.Printf("%T",Struct{}) however this creates a new structure and hence taking up a memory. So I may just print fmt.Printf("main.Struct"), but then suppose somebody refactors the name of the Struct, then the print statement does not get updated and the code breaks.

How could I print a type of a structure without creating its instance?

答案1

得分: 3

其中一种解决方案是使用reflect包:

fmt.Printf("%v", reflect.TypeOf((*Struct)(nil)).Elem())

这段代码不会创建任何结构体的实例。它将打印出main.Struct

英文:

One of the solutions is to use the package reflect:

fmt.Printf("%v", reflect.TypeOf((*Struct)(nil)).Elem())

which does not create any instance of the structure. It will print main.Struct.

答案2

得分: 2

它将始终使用反射来获取类型的名称,没有例外。

在内部,fmt.Printf("%T", x) 使用了 reflect.TypeOf(x)(来源:http://golang.org/src/pkg/fmt/print.go#L721)

你可以使用 fmt.Sprintf,但它仍然使用反射,并增加了解析格式字符串的开销。

name := fmt.Sprintf("%T", (*S)(nil))[1:] //去掉 *
// 或者
name := reflect.TypeOf((*S)(nil)).String()[1:]
英文:

It will always use reflect to get the name of the type, period.

Internally fmt.Printf("%T", x) uses reflect.TypeOf(x) (source: http://golang.org/src/pkg/fmt/print.go#L721)

Use can use fmt.Sprintf but it still uses reflection + the added overhead of parsing the format string.

name := fmt.Sprintf("%T", (*S)(nil))[1:] //lose the *
// or
name := reflect.TypeOf((*S)(nil)).String()[1:]

huangapple
  • 本文由 发表于 2014年9月1日 16:22:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/25601635.html
匿名

发表评论

匿名网友

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

确定