Jonathan Chan
Jonathan Chan

Reputation: 2389

Better way to get the reflect.Type of an interface in Go

Is there an better way to get the reflect.Type of an interface in Go than reflect.TypeOf((*someInterface)(nil)).Elem()?

It works, but it makes me cringe every time I scroll past it.

Upvotes: 4

Views: 262

Answers (1)

Kyle Lemons
Kyle Lemons

Reputation: 4756

Unfortunately, there is not. While it might look ugly, it is indeed expressing the minimal amount of information needed to get the reflect.Type that you require. These are usually included at the top of the file in a var() block with all such necessary types so that they are computed at program init and don't incur the TypeOf lookup penalty every time a function needs the value.

This idiom is used throughout the standard library, for instance:

html/template/content.go: errorType = reflect.TypeOf((*error)(nil)).Elem()

The reason for this verbose construction stems from the fact that reflect.TypeOf is part of a library and not a built-in, and thus must actually take a value.

In some languages, the name of a type is an identifier that can be used as an expression. This is not the case in Go. The valid expressions can be found in the spec. If the name of a type were also usable as a reflect.Type, it would introduce an ambiguity for method expressions because reflect.Type has its own methods (in fact, it's an interface). It would also couple the language spec with the standard library, which reduces the flexibility of both.

Upvotes: 3

Related Questions