gonull

What does nil mean in Golang?


There are many cases using nil in Go. For example:

func (u *URL) Parse(ref string) (*URL, error) {
    refurl, err := Parse(ref)
    if err != nil {
        return nil, err
    }
    return u.ResolveReference(refurl), nil
}

But we can't use it like this:

var str string //or var str int
str = nil

the Go compiler will throw an error:

can't use nil as type string in assignment

Looks like nil can only be used for a pointer of struct and interface. If that is the case, then

In other words, how does Go determine one object is nil?


EDIT

For example, if an interface is nil, its type and value must be nil at the same time. How does Go do this?


Solution

  • In Go, nil is one of the predeclared identifiers and it is a zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.

    nil doesn't mean some "undefined" state, it's a proper value in itself. An object in Go is nil simply if and only if it's value is nil, which it can only be if it's of one of the aforementioned types.

    An error in Go is also one of the predeclared types and it is defined as an interface, so nil is a valid value for one, unlike for a string. A nil error represents no error.