Nil in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

conclusion : Since interface in go stores both type and value, if a nil object is assigned to a interface, the interface is non-nil.

Nil in Go is equivalent to NULL, NULL, and none in other languages, and in actual use indicates that a variable is empty . Nil can only be assigned to variables of the pointer, channel, Func, interface, map, or slice type. Panic will be thrown if nil is assigned to another variable.
First look at a code:

 PackageMainImport "FMT"typeMyerrorstruct{}func(This *myerror) Error ()string{return ""}funcTest () Error {varP *myerror =Nil    /*//check err and Set p if bad () {p = errbad} */    returnPfuncMain () {err: = Test ()ifErr = =Nil{FMT. Println ("Err is nil")    }Else{FMT. Println ("Err is not nil")    }}

The above code will output:

errisNOT nil

This is because, in order to preserve the original data type, in the underlying implementation of go, a interface saves both the original data type and its corresponding values. When assigning a variable of nil to interface, the interface will be stored as {*myerror, nil}. However, the interface variable is nil only if the type and value of the interface are nil.
Or a different way to explain the problem, because nil means that the variable is empty , if it is assigned to interface, then it is no longer empty , so it will not be equal to nil.

Reference:
1. Nil value and nil for error type in Go
2. Golang: detailed interface and nil
3. Go Nil_error

Related Article

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.