对指针使用延迟 [英] Using defer with pointers
问题描述
让我们说我有以下代码:
Let us say that I have the following code:
func getConnection(fileName string) *os.File {
file, err := os.Open(fileName)
//Check for error
return file
}
我使用此函数打开文件,然后从执行其他活动的另一个函数调用该函数.
I use this function to open a file and the function is called from another function that does some other activity.
我的问题是,既然我已经打开文件,如何关闭它.如果我要在 getConnection()
内添加 defer file.Close()
,它会在返回之前关闭文件吗?在调用函数中使用defer有意义吗?
My question is, now that I have opened the file, how do I close it. If I were to add defer file.Close()
inside getConnection()
, wouldn't it close the file before returning? Does it make sense to use defer inside the calling function?
推荐答案
如果函数的目的是返回文件,为什么要在返回文件的函数中将其关闭?
If the purpose of your function is to return a file, why would you want to close it in the function that returns it?
在这种情况下,调用方有责任正确关闭文件,最好使用 defer
:
In this case it is the responsibility of the caller to properly close the file, preferably with defer
:
func usingGetConnection() {
f := getConnection("file.txt")
defer f.Close()
// Use f here
}
尽管您的 getConnection()
函数吞噬了错误,但是您应该使用多次返回值来表示类似这样的问题:
Although your getConnection()
function swallows errors, you should use multi-return value to indicate problems like this:
func getConnection(fileName string) (*os.File, error) {
file, err := os.Open(fileName)
//Check for error
if err != nil {
return nil, err
}
return file, nil
}
并使用它:
func usingGetConnection() {
f, err := getConnection("file.txt")
if err != nil {
panic(err) // Handle err somehow
}
defer f.Close()
// Use f here
}
这篇关于对指针使用延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!