nil在golang中是什么意思?
很多情况下在golang中使用 nil .例如:
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
golang编译器将抛出can't use nil as type string in assignment
错误.
the golang compiler will throw a can't use nil as type string in assignment
error.
类似nil
的外观只能用于struct和interface的指针.如果是这样,那么这是什么意思?
和当我们使用它与另一个对象进行比较时,它们如何进行比较,换句话说,golang如何确定一个对象为零?
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?
例如,如果接口为nil,则其类型和值必须同时为nil. golang如何做到这一点?
在Go中,nil
是指针,接口,映射,切片,通道和函数类型的零值,表示未初始化的值.
In Go, nil
is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.
nil
并不意味着某些未定义"状态,它本身就是一个适当的值.仅当且仅当它的值是nil
时,Go中的对象才是nil
,只有当它是上述类型之一时,它才可以是它.
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.
error
是接口,因此nil
是一个有效值,与string
不同.出于明显的原因,nil
错误表示没有错误.
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.