Home > Backend Development > Golang > How Do I Get the reflect.Type of an Uninitialized Interface in Go?

How Do I Get the reflect.Type of an Uninitialized Interface in Go?

Mary-Kate Olsen
Release: 2024-12-19 11:09:14
Original
281 people have browsed it

How Do I Get the reflect.Type of an Uninitialized Interface in Go?

Determining the reflect.Type of an Interface

To ascertain whether a type implements an interface using the reflect package, it is necessary to provide a reflect.Type to reflect.Type.Implements(). However, obtaining this type can sometimes seem enigmatic, especially for uninitialized interfaces such as error.

Uninitialized Error Interface

Attempting to determine the type of an uninitialized error (interface) using reflect.TypeOf(err).Kind() will result in a panic when Kind() is invoked.

Solution

To correctly obtain the type of an interface like error, it is necessary to first create a pointer to the interface and then use Elem() on the resulting type. This can be accomplished in two ways:

Verbose Method:

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

One-Line Method:

t := reflect.TypeOf((*error)(nil)).Elem()
Copy after login

By following these approaches, you can effectively retrieve the reflect.Type of an interface, regardless of its initialization state.

The above is the detailed content of How Do I Get the reflect.Type of an Uninitialized Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template