This is a creation in Article, where the information may have evolved or changed.
Some time ago when writing code, encountered a strange problem, that is, the return of nil value, not nil.
The reason for this problem is that the nil comprehension of Go is not fully caused, the direct test code is as follows:
package mainimport ( "fmt")// 定义我们自己的 Error 类型type NilErr struct { Code int Msg string}// 实现 error 接口的 Error 方法func (e *NilErr) Error() string { return fmt.Sprintf("Code:%d, Msg:%s", e.Code, e.Msg)}func returnNil() *NilErr { return nil}func main() { fmt.Println("not nil when return nil") var err error err = returnNil() if err != nil { fmt.Println("return of func returnNil is not nil") fmt.Printf("nil type: %T, nil value: %v", err, err) }}
The output of the above program is as follows:
not nil when return nilreturn of func returnNil is not nilnil type: *main.NilErr, nil value: <nil>
As you can see, we declare an error variable err to receive the return value of the function Returnnil, we return nil in the function, but err is not nil, but a type of *main. Nilerr, a variable with a value of nil, and nil in Go is the type value nil, which is obviously not equal.
Official note Why is my nil error value not equal to nil?