On Saturday, 27 November 2021 at 07:55:10 UTC tapi...@gmail.com wrote: > Isn't the code should be: > > *func CopyFile() {* > * ...* > * if err != nil {* > * return* > * }* > > * defer func() { err = src.Close() }()* > * ...* > *}* >
No. Note that the signature of this function (from the original blog post) is: *func CopyFile(dstName, srcName string) (written int64, err error) {* Given that, I think that your proposed change is a bad idea. Either: (1) it may mask the real return error value. For example, if err was set to a non-nil value, but the Close() is successful, err will be set back to nil Or: (2) it will make no difference at all. Whether (1) or (2) applies depends whether the final return is a "naked" one or not. In this case it isn't: *return io.Copy(dst, src)* Therefore, the value returned is whatever io.Copy() returns, so setting "err" in the defer statement makes no difference at all. Your version of the code is more confusing, because it implies that it does something which it doesn't. There is a wider question as to whether you should check the error return from Close() in the first place. In some rare cases it *might* show something, e.g. Close() when you are *writing* a file may return disk full errors for some filesystems. However it doesn't give a guarantee that all errors are caught. If you need to guarantee that the data was successfully written to disk then you should call Fsync() and check the return value of that, but that's an expensive operation (it forces the OS to write dirty buffers to disk). Even then there are issues to beware of, especially if multiple threads are calling Fsync() on the same file. See https://www.youtube.com/watch?v=74c19hwY2oE https://wiki.postgresql.org/wiki/Fsync_Errors # both linked from: https://docs.ceph.com/en/mimic/cephfs/posix/ Most applications don't need this type of guarantee, i.e. if the disk becomes full or there are I/O errors then they accept that the data on disk will be corrupt. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/774265d3-f574-4bf7-bef7-ece3cd79643bn%40googlegroups.com.