我们说我有以下代码:
func getConnection(fileName string) *os.File {
file, err := os.Open(fileName)
//Check for error
return file
}
我使用此函数打开一个文件,并从另一个执行其他活动的函数调用该函数。
我的问题是,现在我已经打开了文件,如何关闭它。如果我要在defer file.Close()
内添加getConnection()
,在返回之前是不是会关闭文件?在调用函数中使用defer是否有意义?
答案 0 :(得分:9)
如果你的函数的目的是返回一个文件,你为什么要在返回它的函数中关闭它呢?
在这种情况下,调用者负责正确关闭文件,最好使用defer
:
func usingGetConnection() {
f := getConnection("file.txt")
defer f.Close()
// Use f here
}
虽然您的getConnection()
函数会吞下错误,但您应该使用多重返回值来表示这样的问题:
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
}