Reputation: 11238
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.
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?
Upvotes: 3
Views: 584
Reputation: 418745
If the purpose of your function is to return a file, why would you want to close it in the function that returns it?
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
}
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
}
And using it:
func usingGetConnection() {
f, err := getConnection("file.txt")
if err != nil {
panic(err) // Handle err somehow
}
defer f.Close()
// Use f here
}
Upvotes: 9