Nil in the Go language

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

This article is Francesc Campoy on the GoConf Understanding Nil Lecture notes.

(1) nil no type .

(2) in a Go language, variables that do not appear to be initialized have their type zero value . 6the common types of variables zero value are:,,, nil pointer slice map channel , function and interface . The specific meanings are as follows:

type Nil value meaning
Pointer Point to Nothing
Slice 3 member values in the slice variable: buf is nil (no backing array), Len and Cap are all 0
Map,channel,function A nil pointer, pointing to Nothing
Interface Interface contains "type, value", and a nil interface must both be nil: "Nil, nil"

For that interface reason, the value is just because <type, value> two values in this tuple are needed nil interface nil . So pay attention to the following two points:

A) do not declare concrete error VARs:

func do() error {    var err *doError // nil of type *doError    return err // error (*doError, nil)}func main() {    err := do() // error (*doError, nil)    fmt.Println(err == nil) // false}

b) do not return concrete error types:

func do() *doError {    return nil // nil of type *doError}func main() {    err := do() // nil of type *doError    fmt.Println(err == nil) // true}func do() *doError {    return nil // nil of type *doError}func wrapDo() error { // error (*doError, nil)    return do() // nil of type *doError}func main() {    err := wrapDo() // error (*doError, nil)    fmt.Println(err == nil) // false}

(3) nil Some useful usage scenarios:

type Nil Value usage scenario
Pointer Methods can called on nil receivers
Slice Perfectly valid zero values
Map Perfect as read-only values (adding members to nil map will cause panic)
Channel Essential for some concurrency patterns
function Needed for completeness
Interface The most used signal in Go (err! = nil)

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.