david
david

Reputation: 2717

Print type of a structure without creating its instance

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?

Upvotes: 1

Views: 946

Answers (2)

OneOfOne
OneOfOne

Reputation: 99234

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:]

Upvotes: 2

david
david

Reputation: 2717

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.

Upvotes: 3

Related Questions