nilis apredeclared identifierliketrue,false,len(),int32,float64etc.Since it is a
predeclared identifier, it can be used anywherewithout importinganypackage.nil valuemeans that the value isnot initializedyet.It is similar to following identifiers in other languages:
null // JavaScript None // Python null // Java nil // RubyThe
zero valueof allpointer-basedtypes in Go isnil. Following are thepointer-basedtypes in Go:- pointers
- slices
- maps
- interfaces
- channels
In Go,
nilvalue can beuntypedortypeddepending on thecontext.
Nil in error handling
In Go,
nilvalue is extensively used for Error Handling.For e.g.
func main() { data, err := someFunc() if err != nil { fmt.Println("Error occurred") return } else { fmt.Println("Success") } }