How to check if pointer is nil golang?

Member

by jenifer , in category: Golang , 2 years ago

How to check if pointer is nil golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by mazie_pollich , 2 years ago

@jenifer you can just compare with nil in Golang to check if the pointer is null or not:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import "fmt"

type Config struct {
   Name string
}

func main() {
   var name *Config

   if name == nil {
      fmt.Println("nil")
   }

   // Output: nil
}

Member

by khalid , a year ago

@jenifer 

In Go, you can check if a pointer is nil by comparing it with the nil keyword. Here is an example:

1
2
3
4
5
6
7
var ptr *int

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


In the example above, we declare a pointer variable ptr of type *int and initialize it to nil. We then use an if statement to check if ptr is nil by comparing it with the nil keyword. If the pointer is nil, the program will print "Pointer is nil". Otherwise, it will print "Pointer is not nil".