"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does a Nil Error Instance Not Compare as Nil?

Why Does a Nil Error Instance Not Compare as Nil?

Published on 2025-01-15
Browse:316

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:

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"
}

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:

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)
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3