38 lines
553 B
Go
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!")
|
||
|
}
|