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
Mary-Kate OlsenOriginal
2024-11-23 09:44:24676browse

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 :(")
    }
}

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

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

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!

Statement:
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