Defer Stack

Correct a mistake about defer in the code below

  1. package main
  2. import (
  3. "io/ioutil"
  4. "os"
  5. )
  6. func main() {
  7. f, err := os.Open("file")
  8. defer f.Close()
  9. if err != nil {
  10. return
  11. }
  12. b, err := ioutil.ReadAll(f)
  13. println(string(b))
  14. }

Answer

  1. package main
  2. import (
  3. "io/ioutil"
  4. "os"
  5. )
  6. func main() {
  7. f, err := os.Open("file")
  8. if err != nil {
  9. return
  10. }
  11. defer f.Close()
  12. b, err := ioutil.ReadAll(f)
  13. println(string(b))
  14. }