gobyexample/defers/defers.go
2024-05-01 18:55:16 +05:30

38 lines
553 B
Go

package defers
import (
"fmt"
"os"
)
func Defers() {
f := createFile("/tmp/defers.go.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(path string) *os.File {
f, err := os.Create(path)
if err != nil {
panic(err)
}
return f
}
func closeFile(f *os.File) {
fmt.Println("Closing file")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "something went wrong closing file: %v\n", err)
os.Exit(1)
}
}
func writeFile(f *os.File) {
fmt.Println("Writing something to the file")
fmt.Fprintln(f, "Hello from defers.go!")
}