Add defer
This commit is contained in:
parent
36574bafdf
commit
f1fe463b05
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!")
|
||||||
|
}
|
6
main.go
6
main.go
@ -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()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user