Home > Article > Backend Development > 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:
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!