Home > Article > Backend Development > Why does comparing a nil interface with `nil` fail in Go?
Interfaces and Type Comparisons in Go
In Go, interfaces provide a way to define a common set of methods that different types can implement. However, it's important to understand how interface comparisons work to avoid unexpected behavior.
Consider the following 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) // expect "Error is nil" }</code>
In this example, we create a custom type Goof that implements the error interface. We then pass a nil pointer of type *Goof to a function TestError that expects an error. Counterintuitively, the program does not print "Error is not nil."
This is because interface comparisons not only check the value but also the type. In this case, the nil instance of *Goof is of a different type than the error interface. Therefore, the comparison err == nil fails.
To overcome this issue, there are several options. One is to declare err as a variable of type error directly:
<code class="go">var err error = g</code>
Another option is to return nil from your function if an error occurs:
<code class="go">func MyFunction() error { // ... if errorOccurred { return nil } // ... }</code>
By understanding how interface comparisons work, you can avoid potential pitfalls and write more effective Go code.
The above is the detailed content of Why does comparing a nil interface with `nil` fail in Go?. For more information, please follow other related articles on the PHP Chinese website!