Consider the following code:
f, err := os.Create(tmpFilepath)
defer f.Close()
// do some writing to f
os.Rename(tmpFilepath, newpath)
Some error handling has been removed to simplify.
Also, I know this code is wrong, but I am trying to understand what is the effect of this code in term of correctness of the files, and in terms of performance.
Is there a resource leak here?
By the way, the fix is to close when you are done writing to the file.
If we're talking with an OS and filesystem implementing POSIX semantics (that is, not Windows which normally would not allow you to rename an opened file), there is absolutely no problem: an open file descriptor merely counts as a hardlink to the file's data.
That data of the renamed file does not somehow gets detached from the opened file descriptor—consider the latter as a sort of "anonymous" reference to that data.
To cite the close(2)
manual:
If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the file shall no longer be accessible.