Add defer

This commit is contained in:
Sangeeth Sudheer 2024-05-01 18:55:16 +05:30
parent 36574bafdf
commit f1fe463b05
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 41 additions and 2 deletions

37
defers/defers.go Normal file
View 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!")
}

View File

@ -19,7 +19,8 @@ package main
// import "git.sangeeth.dev/gobyexample/mutex" // import "git.sangeeth.dev/gobyexample/mutex"
// import "git.sangeeth.dev/gobyexample/statefulgoroutines" // import "git.sangeeth.dev/gobyexample/statefulgoroutines"
// import "git.sangeeth.dev/gobyexample/sorting" // import "git.sangeeth.dev/gobyexample/sorting"
import "git.sangeeth.dev/gobyexample/panic" // import "git.sangeeth.dev/gobyexample/panic"
import "git.sangeeth.dev/gobyexample/defers"
func main() { func main() {
// runes.Runes() // runes.Runes()
@ -41,5 +42,6 @@ func main() {
// mutex.Mutex() // mutex.Mutex()
// statefulgoroutines.StatefulGoroutines() // statefulgoroutines.StatefulGoroutines()
// sorting.Sorting() // sorting.Sorting()
panic.Panic() // panic.Panic()
defers.Defers()
} }