How to Check Nil in Golang

To check if a variable is nil in Go, you can use the “comparison operator(==)”. The nil value is zero for pointers, functions, interfaces, maps, slices, and channels. When a variable of these types is not initialized, its value is nil.

Example

package main

import (
  "fmt"
)

func main() {
  var ptr *int // Pointer
  var intf interface{} // Interface
  var slc []string // Slice
  var mp map[string]int // Map
  var fn func() // Function
  var ch chan int // Channel

  if ptr == nil {
    fmt.Println("Pointer is nil")
  }

  if intf == nil {
    fmt.Println("Interface is nil")
  }

  if slc == nil {
    fmt.Println("Slice is nil")
  }

  if mp == nil {
    fmt.Println("Map is nil")
  }

  if fn == nil {
    fmt.Println("Function is nil")
  }

  if ch == nil {
    fmt.Println("Channel is nil")
  }
}

Output

Pointer is nil
Interface is nil
Slice is nil
Map is nil
Function is nil
Channel is nil

In this example, we declared several variables of different types, including a pointer, interface, slice, map, function, and channel.

In the next step, we used the == operator to compare each variable to nil and printed a message if the variable was nil.

It’s essential to check for nil before trying to access or modify the contents of pointers, interfaces, maps, slices, or channels. Attempting to access or modify a nil value will result in a runtime panic.

That’s it.