What does nil mean in golang?

后端 未结 7 1009
爱一瞬间的悲伤
爱一瞬间的悲伤 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:30

    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.

    0 讨论(0)
  • 2020-12-24 06:30

    nil is also a value but only difference is- it is empty.

    In Javascript for the un-initialized variable will be undefined. In the same way Golang has nil as default value for all the un-initalized data types.

    0 讨论(0)
  • 2020-12-24 06:41

    In Golang, datatype can use nil is pointers, interfaces, maps, slices, channels, function types and errors

    in String value is ""

    in INT value is ZERO

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 06:48

    nil in Go means a zero value for pointers, interfaces, maps, slices, and channels. It means the value is uninitialized

    0 讨论(0)
  • 2020-12-24 06:49
    • For the data types like slice and pointers which "refer" to other types, "nil" indicates that the variable does not refer to an instance (equivalent of null pointer in other languages)
    • It is thee zero value of the variables of type functions, maps, interfaces, channels and structures
    0 讨论(0)
提交回复
热议问题