Contents
14. Defer(退出处理)¶
在Go中进行延迟的很酷的事情是,您可以在重要的地方键入该内容,然后让读者清楚地知道它将在以后执行。
在Python中,您可以通过将try:和finally:块之间的内容保持简短来实现相同的目的。
14.1. Python¶
f = open("defer.py", encoding="utf-8")
try:
f.read()
finally:
f.close()
14.2. Go¶
package main
import "os"
func main() {
f,_ := os.Open("defer.py")
defer f.Close()
// you can now read from this
// `f` thing and it'll be closed later
}