1
0
Fork 0
pr3-sose2026-fork/go/02-next-level/06-defer.go

42 lines
735 B
Go

package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("creating")
f, err := os.Create("/tmp/defer.txt")
// defer the closing of the file until the surrounding function returns.
// This ensures that the file will be closed even if there is a panic or an early return in the function.
defer closeFile(f)
if err != nil {
panic(err)
}
//will not be called in case of a panic before
writeFile(f)
// closeFile will be called here due to the defer-statement, even in case of a panic before.
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
func closeFile(f *os.File) {
fmt.Println("closing")
var err error
if f != nil {
err = f.Close()
}
if err != nil {
panic(err)
}
}