英文:
Does the assignment to blank identifier lead to resource leak in Go?
问题
如果我获取了一些可关闭的资源(例如*os.File
)并将其分配给空白标识符(_
),会发生什么?根据这个SO答案,没有办法访问这个变量,所以它将被优化掉,不会出现在最终的程序中。但是它会被正确关闭吗?下面是示例代码。
func check(path string) bool {
_, err := os.Open(path)
if err != nil {
return true
}
return false
}
英文:
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
}
答案1
得分: 4
无论您将文件分配给空白标识符还是命名变量,如果您不显式调用其Close()
方法,它将不会被关闭并且会泄漏资源。
如果您将返回的*os.File
分配给空白标识符,您将无法引用它,因此无法调用其Close()
方法。所以不要这样做。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论