Home  >  Article  >  Backend Development  >  Why Does `nil` Interface Value Not Equal `error(nil)` in Go?

Why Does `nil` Interface Value Not Equal `error(nil)` in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 18:45:30615browse

Why Does `nil` Interface Value Not Equal `error(nil)` in Go?

Comparison of Nil Interface Instances

Consider the below code:

<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) // Displays "Error is not nil"
}</code>

Surprisingly, this code results in "Error is not nil", despite the intention to test for the nil condition.

The key to understanding this behavior lies in how Go implements interfaces. Internally, interface values consist of a type and a value. While the value may be nil, the type is never nil. In the given example, (*Goof)(nil) is an interface value with the type "*Goof" and the nil value.

However, the error interface type is distinct from the "*Goof" type. Therefore, (*Goof)(nil) and error(nil) are not equal, even though they both contain nil values. This is evident from the following code:

<code class="go">var g *Goof // nil
var e error = g

if e == nil {
    fmt.Println("Error is nil")
} else {
    fmt.Println("Error is not nil")
}
// Output: Error is not nil</code>

To resolve this issue, there are multiple approaches:

  1. Declare var err error instead of var g *Goof, as err's zero value is conveniently error(nil).
  2. If the function returns an error, using return nil will return the desired nil interface value.

The above is the detailed content of Why Does `nil` Interface Value Not Equal `error(nil)` in Go?. 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