Home  >  Article  >  Backend Development  >  Why Does a Nil Error Instance Not Compare as Nil?

Why Does a Nil Error Instance Not Compare as Nil?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 06:51:281007browse

Why Does a Nil Error Instance Not Compare as Nil?

Nil Error Instances Not Displaying as Nil

In understanding interface comparisons, it's crucial to recognise that they evaluate both the type and the value.

Consider the code snippet:

<code class="go">type Goof struct {}

func (goof *Goof) Error() string {
    return fmt.Sprintf("I'm a goof")
}

func TestError(err error) {
    if err == nil {
        fmt.Println("Error is nil")
    } else {
        fmt.Println("Error is not nil")
    }
}

func main() {
    var g *Goof // nil
    TestError(g) // expect "Error is nil"
}</code>

Here, we expect "Error is not nil" since g is nil. However, due to interface comparisons, we get "Error is nil". This is because (*Goof)(nil) has a different type than error(nil).

To resolve this, you can declare var err error instead of var g *Goof. Alternatively, if your function returns an error, simply return nil.

For further clarification, interface comparisons check if the types are identical, not if a type implements an interface. As such, the following example demonstrates that even non-nil interfaces with the same underlying data can compare as unequal due to different types:

<code class="go">package main

import "fmt"

type Bob int

func main() {
    var x int = 3
    var y Bob = 3
    var ix, iy interface{} = x, y
    fmt.Println(ix == iy)
}</code>

The above is the detailed content of Why Does a Nil Error Instance Not Compare as Nil?. 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