Does the assignment to blank identifier lead to resource leak in Go?

huangapple go评论87阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年11月25日 19:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70110719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定