Comment

Comment by nickcw

Here is my favorite solution to this problem

  // CheckClose is a utility function used to check the return from
  // Close in a defer statement.
  func CheckClose(c io.Closer, err *error) {
          cerr := c.Close()
          if *err == nil {
                  *err = cerr
          }
  }

Use like this - you must name the error return

  func whatever() (err error) {
      f, err := os.Open(blah)
      // ...
      defer CheckClose(f, &err)
      // ...
  }
This closes the file and if there wasn't an existing error, writes the error from f.Close() in there.
parent nickcw 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton