Error handling intro

  • nil is a predeclared identifier like true, false, len(), int32, float64 etc.

  • Since it is a predeclared identifier, it can be used anywhere without importing any package.

  • nil value means that the value is not initialized yet.

  • It is similar to following identifiers in other languages:

    null    // JavaScript
    None    // Python
    null    // Java
    nil     // Ruby
    
  • The zero value of all pointer-based types in Go is nil. Following are the pointer-based types in Go:

    • pointers
    • slices
    • maps
    • interfaces
    • channels
  • In Go, nil value can be untyped or typed depending on the context.

Nil in error handling

  • In Go, nil value 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")
        }
    }
    

See also