It seems that os.Open()
open read-only files. So I think there is no need to Close()
it. The doc is not clear on this. Is my understanding correct?

- 19,337
- 4
- 43
- 52

- 11,937
- 17
- 63
- 152
4 Answers
In general, you should always close the files you open. In a long running program, you may exhaust all available file handles if you do not close your files. That said, the Go garbage collector closes open files, so depending on your exact situation leaving files open may not be a big deal.

- 46,455
- 3
- 40
- 59
-
1It is done by setting a finalizer: https://stackoverflow.com/questions/8595457/which-objects-are-finalized-in-go-by-default-and-what-are-some-of-the-pitfalls-o – Burak Serdar Jul 19 '20 at 22:55
-
1I know how it's implemented. My point is that it's not part of the standard, it would be ideal to have a reference to a current standard library code, since it may change at some point. – zerkms Jul 19 '20 at 22:57
-
1https://golang.org/src/os/file_unix.go it is at the end of newFile(). Same thing exists in file_windows.go. – Burak Serdar Jul 19 '20 at 23:00
There is a limit to how many filehandles a process can have open at once, the limit is determined by your environment, so it's important to close them.
In addition, Windows file locking is complicated; if you hold a file open it may not be able to be written to or deleted.
Unless you're returning the open filehandle, I'd advise to always match an open with a defer file.Close()

- 153,029
- 25
- 195
- 336
Close releases resources that are independent of the read/write status of the file. Close the file when you are done with it.

- 11
- 1
Your best bet is to always use defer file.Close()
. This function is invoked for cleanup purposes, and also releases resources that are indirectly related to the I/O operation itself.
This also holds true to HTTP/s response bodies and any data type that implements the Reader interface.

- 200
- 1
- 6