Defer
// Importing necessary packages.
import (
"fmt"
"os"
)
// The main function, where the execution of the program begins.
func main() {
// Creating a file and deferring the closing of the file until the surrounding function returns.
f := createFile("/tmp/defer.txt")
defer closeFile(f)
// Writing data to the file.
writeFile(f)
}
// createFile function creates a file and returns a pointer to the os.File.
func createFile(p string) *os.File {
fmt.Println("creating")
// Attempting to create the file.
f, err := os.Create(p)
if err != nil {
// If an error occurs during file creation, the program panics.
panic(err)
}
return f
}
// writeFile function writes data to the provided os.File.
func writeFile(f *os.File) {
fmt.Println("writing")
// Writing the data to the file.
fmt.Fprintln(f, "data")
}
// closeFile function closes the provided os.File, handling errors.
func closeFile(f *os.File) {
fmt.Println("closing")
// Closing the file and checking for errors.
err := f.Close()
// Handling errors if the file cannot be closed successfully.
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}Output
Last updated