Small mouth gnawing Golang-returned nil not nil for the doubt

Source: Internet
Author: User
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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.