What if I acquire some closable resource (e.g. *os.File
) and assign it to the blank identifier (_
)? According to this SO answer, there is no way to access this variable so it will be optimised out of the resulting program. But will it be closed correctly? Example code below.
func check(path string) bool {
_, err := os.Open(path)
if err != nil {
return true
}
return false
}
CodePudding user response:
No matter if you assign the file to the blank identifier or to a named variable, if you don't call its Close()
method explicitly, it will not be closed and will leak resources.
If you assign the returned *os.File
to the blank identifier, you can't refer to it thus you can't call its Close()
method. So don't do it.