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

  1. f = open("defer.py")
  2. try:
  3. f.read()
  4. finally:
  5. f.close()

Go

  1. package main
  2.  
  3. import (
  4. "os"
  5. )
  6.  
  7. func main() {
  8. f, _ := os.Open("defer.py")
  9. defer f.Close()
  10. // you can now read from this
  11. // `f` thing and it'll be closed later
  12.  
  13. }