英文:
How to check whether the value of a pointer is nil or not in golang?
问题
我有一个使用argparse的golang
项目,它接受一个可选的文件作为参数。该文件是使用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 (
"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()
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论