Home > Backend Development > Golang > How Can I Safely Pass Nil Interface Values Using Go Reflection?

How Can I Safely Pass Nil Interface Values Using Go Reflection?

Mary-Kate Olsen
Release: 2024-11-23 09:44:24
Original
663 people have browsed it

How Can I Safely Pass Nil Interface Values Using Go Reflection?

Passing Nil Values as Interfaces via Reflection

Reflecting upon interfaces presents the challenge of passing nil values effectively. Consider the following function:

func f(e error) {
    if e == nil {
        fmt.Println("YEY! NIL") // Aim for this
    } else {
        fmt.Println("NOT NIL :(")
    }
}
Copy after login

If you attempt to pass a nil value to the function via reflection using the below code, it will result in a panic:

nilArg := reflect.Zero(reflect.TypeOf((error)(nil)))
Copy after login

Don't despair! To bypass the issue, utilize the expression reflect.TypeOf((*error)(nil)).Elem() to obtain the reflect.Type for the interface error. This trick involves passing a non-interface value to reflect.TypeOf() and using reflect.Elem() to derive the desired type.

For the nilArg construction, employ the following:

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

Enjoy a working playground example to solidify your understanding.

The above is the detailed content of How Can I Safely Pass Nil Interface Values Using Go Reflection?. 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