Defer
The cool thing about defer
in Go is that you can type that nearwhere it matters and it's then clear to the reader that it will dothat later.
In Python you can sort of achive the same thing by keeping the contentbetween the try:
and the finally:
block short.
Python
- f = open("defer.py")
- try:
- f.read()
- finally:
- f.close()
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
- }