4 ms·
TL;DR - defer Close ignores the error from Close, so don't.
by karmakaze 2y ago
TL;DR - defer Close ignores the error from Close, so don't.
- klodolph 2y agoEh, the real answer is close twice (as in the article update): func f(filename string) error { fp, err := os.Create(filename) if err != nil { return err } defer fp.Close() if _, err := fmt.Fprintln(fp, "Hello, world!"); err != nil { return err } return fp.Close() // safe to call multiple times } The .Close() method is safe to call multiple times. This behavior is documented on the os.File
- jagrsw 2y agoIt might be well implementation-dependent. On Linux, the close() system call rarely fails unless you provide an invalid file descriptor. L.Torvalds has stated that on Linux, close() immediately removes the file descriptor from the process, regardless of the underlying implementation's success or failure. Any errors related to the actual closing of the file are handled within the kernel and won't affect user-space programs. I know that go Close is not posix/linux close, but in majority of cases it'll boil down to it. To quote: Retrying the close() after a failure return is the wrong thing to do, since this may cause a reused file descriptor from another thread to be closed. This can occur because the Linux kernel always releases the file descriptor early in the close operation, freeing it for reuse; the steps that may return an error, such as flushing data to the filesystem or device, occur only later in the close operation. Many other implementations similarly always close the file descriptor (except in the case of EBADF, meaning that the file descriptor was invalid) even if they subsequently report an error on return from close(). POSIX.1 is currently silent on this point, but there are plans to mandate this behavior in the next major release of the standard.