Use of defer in Go
The defer keyword in Go allows you to execute a function just before the surrounding function returns, ensuring actions are taken even in the event of a panic.
Benefits of defer Over Code Placed at Function End
Examples:
Try-finally Resource Cleanup:
func main() { f, err := os.Create("file") if err != nil { panic("cannot create file") } defer f.Close() fmt.Fprintf(f, "hello") }
Try-catch-finally with Panic Handling:
func main() { defer func() { msg := recover() fmt.Println(msg) }() f, err := os.Create(".") // . is the current directory if err != nil { panic("cannot create file") } defer f.Close() fmt.Fprintf(f, "hello") }
Modified Return Values:
func yes() (text string) { defer func() { text = "no" }() return "yes" } func main() { fmt.Println(yes()) // Prints "no" }
In summary, defer in Go provides a flexible way to ensure resource cleanup, handle panics, and control execution order without the need for nested block structures.
The above is the detailed content of How Does Go's `defer` Keyword Simplify Resource Management and Panic Handling?. For more information, please follow other related articles on the PHP Chinese website!