.Close
method GO-S2307Calling Close()
method may return an error, and ignoring the same
might result in a data loss. This is similar to many more Close
methods.
For example, on POSIX systems, os.Close
uses the close
system call underneath,
which may return an EIO
:
A previously-uncommitted write(2) encountered an input/output error.
This means that the data written by os.Write
hasn't been written to the disk,
which results in a data loss. It is recommended to handle the error returned
by the os.Close
call or call os.Sync
if available to force the OS to write
the data to the disk.
package main
import (
"fmt"
"os"
)
func foo() error {
f, err := os.Create("/tmp/test.txt")
if err != nil {
return err
}
defer f.Close()
return fmt.Fprint(f, "Hello World")
}
package main
import (
"fmt"
"os"
)
func foo() error {
f, err := os.Create("/tmp/test.txt")
if err != nil {
return err
}
err = fmt.Fprint(f, "Hello World")
if err != nil {
return err
}
return f.Close()
}
package main
import (
"fmt"
"os"
)
func foo() error {
f, err := os.Create("/tmp/test.txt")
if err != nil {
return err
}
defer f.Close()
err = fmt.Fprint(f, "Hello World")
if err != nil {
return err
}
return f.Sync()
}