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

huangapple go评论70阅读模式
英文:

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

问题

我有一个使用argparsegolang项目,它接受一个可选的文件作为参数。该文件是使用File标志检索的,可能会为文件分配一些内存。代码如下:

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()
	}
}

当我运行命令时,输出为:

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

提示我正在解引用一个nil指针,但是当我检查指针是否为nil时,它说它不是,尽管Println返回一个具有nil值的指针。我该如何检查我的文件指针的内容是否为nil

注意:错误来自于myFile.Stat()。

英文:

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 (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;os&quot;

	&quot;github.com/akamensky/argparse&quot;
)

func main() {
	parser := argparse.NewParser(&quot;&quot;, &quot;&quot;)

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

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

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

When I run my command, my output is

&amp;{&lt;nil&gt;}
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()

答案1

得分: 1

你正在使用的库提供了一个用于检查的函数。你需要这样做:

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

这是必要的,因为File函数返回一个指向空的os.File对象的指针,而且由于你将标志标记为可选的,如果你在命令行中没有提供标志,这个对象将保持为空,而不会出现解析错误。显然,在空的os.File对象上调用Stat是行不通的,这就是为什么你会得到无效的内存地址的原因。

英文:

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.

huangapple
  • 本文由 发表于 2021年9月23日 04:22:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/69290837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定