Add defer
This commit is contained in:
37
defers/defers.go
Normal file
37
defers/defers.go
Normal file
@@ -0,0 +1,37 @@
|
||||
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!")
|
||||
}
|
||||
Reference in New Issue
Block a user