What does nil mean in golang?


There are many cases using nil in golang. 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 golang compiler will throw a can't use nil as type string in assignment error.

Looks like nil can only be used for a pointer of struct and interface. If that is the case, then what does it mean?
and when we use it to compare to the other object, how do they compare, in other words, how does golang 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 golang do this?


In Go, nil is the 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 is an interface, so nil is a valid value for one, unlike for a string. For obvious reasons a nil error represents no error.

Answered By – LemurFromTheId

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.