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())
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.
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.
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.
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.
Do it like this:
var err error t := reflect.TypeOf(&err).Elem()
Or in one line:
t := reflect.TypeOf((*error)(nil)).Elem()
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With