Home > other >  How to check whether the value of a pointer is nil or not in golang?
How to check whether the value of a pointer is nil or not in golang?

Time:09-24

I have a golang project using argparse which takes a not required file as argument. The file is retrieved with File flag which may be allocating some memory for a file. code :

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/akamensky/argparse"
)

func main() {
    parser := argparse.NewParser("", "")

    myFile := parser.File("", "file", os.O_RDONLY, 0444, &argparse.Options{Required: false})

    if err := parser.Parse(os.Args); err != nil {
        log.Fatalf("error at parsing: %v", err)
    }

    if myFile != nil {
        fmt.Println(myFile)
        myFile.Stat()
    }
}

When I run my command, my output is

&{<nil>}
panic: runtime error: invalid memory address or nil pointer dereference

Saying I'm dereferencing a nil pointer but when I check whether the pointer is nil or not it says it is not although the Println returns a pointer with nil value. How can I check if the content of my file pointer is nil or not ?

NB: the error comes from myFile.Stat()

CodePudding user response:

The library you are using provides a function for checking this. You need to do:

if !argparse.IsNilFile(myFile) {
    fmt.Println(myFile)
    myFile.Stat()
}

This is necessary because the File function returns a pointer to an empty os.File object, and since you've marked your flag as optional, this object will remain empty without parsing errors if you don't provide your flag at the command line. Stat obviously isn't going to work on an empty os.File object, and that's why you're getting your invalid memory address.

  • Related