How to check pointer or interface is nil or not in Golang?


In Golang, we often come across situations where we need to check whether a pointer or interface is nil or not. A pointer is a memory address pointing to a variable or data type, while an interface is a set of methods that define a particular behavior. In this article, we will discuss how to check whether a pointer or interface is nil or not in Golang.

How to check if a pointer is nil or not in Golang?

To check whether a pointer is nil or not in Golang, we can use the comparison operator ‘==’ to compare it with nil. If the pointer is nil, the comparison will return true; otherwise, it will return false. Here's an example −

Example

package main

import "fmt"

func main() {
   var ptr *int

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

Output

Pointer is nil

In the above code, we declare a pointer variable 'ptr' of type int and don't assign it any value. Then we use the comparison operator '==' to check whether it is nil or not. Since 'ptr' is not assigned any value, it is nil, and the output will be "Pointer is nil."

How to check if the interface is nil or not in Golang?

To check whether an interface is nil or not in Golang, we can use the same comparison operator '==' to compare it with nil. If the interface is nil, the comparison will return true; otherwise, it will return false. Here's an example −

Example

package main

import "fmt"

func main() {
   var inf interface{}

   if inf == nil {
      fmt.Println("Interface is nil")
   } else {
      fmt.Println("Interface is not nil")
   }
}

Output

Interface is nil

In the above code, we declare an interface variable 'inf' and don't assign it any value. Then we use the comparison operator '==' to check whether it is nil or not. Since 'inf' is not assigned any value, it is nil, and the output will be "Interface is nil."

Conclusion

In Golang, we can use the comparison operator '==' to check whether a pointer or interface is nil or not. If the comparison returns true, it means that the pointer or interface is nil; otherwise, it is not nil. We can use this technique to handle nil pointer or interface values in our code effectively.

Updated on: 19-Apr-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements