为什么错误与nil不匹配? 走

Why when you use negatively compare an error with nil if provides the expected output but when you try to compare it using the 'positive' operator it 'doesn't work'? I think the code See below

package main

import "fmt"
import "errors"

func main() {
    err := makeError
    if err != nil {
        fmt.Println("as expected")

        err = noError
        if err == nil {
            fmt.Println("as expected")
        } else {
            fmt.Println("Why no error ?")
        }
    }
}

func makeError() error {
    return errors.New("error!")
}

func noError() (err error) {
    return
}

Play this thing!

In your example code, err is not an error value. With the following assignment:

err := makeError

err is of type func() error. The err != nil succeeds because the makeError function is not nil. Similarly, noError is also a function and not equal to nil.

If you actually call the functions, you should get the results you expected.

The problem is that you don't call your functions, but assign the function itself to your variables. So the err value is always different from nil.

Example:

func foo() error {
    return nil
}

func bar() error {
    return errors.New("error")
}

// err will be the same as the foo function
// you can then do err()
err := foo

// err will be an error var, nil in this case
// err != nil will return false
err := foo()

// err will be an error var, equivalent to errors.New("error")
err := bar()

If you try to create the variable then assign to it, your compiler will yell at you (as expected). Example:

func foo() error {
    return nil
}

var err error
err = foo

will give you the following compiler error

cannot use foo (type func() error) as type error in assignment: func() error does not implement error (missing Error method)

In the playground