Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the reflect.Type of an interface?

Tags:

go

In order to determine whether a given type implements an interface using the reflect package, you need to pass a reflect.Type to reflect.Type.Implements(). How do you get one of those types?

As an example, trying to get the type of an uninitialized error (interface) type does not work (it panics when you to call Kind() on it)

var err error fmt.Printf("%#v\n", reflect.TypeOf(err).Kind()) 
like image 440
laslowh Avatar asked Aug 20 '11 15:08

laslowh


People also ask

What is reflection interface?

Interfaces store type information when assigned a value. Reflection is a method of examining type and value information at runtime. Go implements reflection with the reflect package which provides types and methods for inspecting portions of the interface structure and even modifying values at runtime.

What is reflect value?

Reflection is provided by the reflect package. It defines two important types, Type and Value . A Type represents a Go type. It is an interface with many methods for discriminating among types and inspecting their components, like the fields of a struct or the parameters of a function.

What is reflect in Go?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose. Reflection is often termed as a method of metaprogramming.

What is reflect indirect?

The reflect. Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.


2 Answers

Do it like this:

var err error t := reflect.TypeOf(&err).Elem() 

Or in one line:

t := reflect.TypeOf((*error)(nil)).Elem() 
like image 127
Evan Shaw Avatar answered Sep 28 '22 01:09

Evan Shaw


Even Shaws response is correct, but brief. Some more details from the reflect.TypeOf method documentation:

// As interface types are only used for static typing, a common idiom to find // the reflection Type for an interface type Foo is to use a *Foo value.  writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()  fileType := reflect.TypeOf((*os.File)(nil)).Elem() fmt.Println(fileType.Implements(writerType)) 
like image 21
Kristoffer Avatar answered Sep 28 '22 01:09

Kristoffer