patterngoCritical
What does nil mean in Golang?
Viewed 0 times
nildoesgolangmeanwhat
Problem
There are many cases using
But we can't use it like this:
the Go compiler will throw an error:
Looks like
In other words, how does Go determine one object is
EDIT
For example, if an interface is
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 = nilthe Go compiler will throw an error:
can't use nil as type string in assignmentLooks like
nil can only be used for a pointer of struct and interface. If that is the case, then- what does it mean?
- when we use it to compare to the other object, how do they compare?
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,
An
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.Context
Stack Overflow Q#35983118, score: 187
Revisions (0)
No revisions yet.