What does nil mean in golang?

后端 未结 7 1011
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 06:12

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

func (u *URL) Parse(ref string) (*URL, error) {
    refurl, err := Parse(ref)
    if          


        
7条回答
  •  甜味超标
    2020-12-24 06:42

    nil in Go is simply the NULL pointer value of other languages.

    You can effectively use it in place of any pointer or interface (interfaces are somewhat pointers).

    You can use it as an error, because the error type is an interface.

    You can't use it as a string because in Go, a string is a value.

    nil is untyped in Go, meaning you can't do that:

    var n = nil
    

    Because here you lack a type for n. However, you can do

    var n *Foo = nil
    

    Note that nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.

提交回复
热议问题