How to get the reflect.Type of an interface?

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))

Tags:

Go