Home > Article > Backend Development > When and How Can Defer Statements Be Used in Go?
Go Idioms and Examples
As a language learner exploring Go, you may encounter unique constructs and idioms. Here's a list to enhance your understanding:
Defer Statements
The "defer" statement allows you to defer function execution until the surrounding function returns. It's convenient for cleanup tasks, locking/unlocking resources, or exception handling.
For example:
func doSomething() { funcToDefer() } func funcToDefer() { fmt.Println("Called after doSomething returns") }
In this example, "funcToDefer" will be executed after "doSomething" completes.
Panic Handling with Defer
Defer is also used for panic recovery. You can defer a function to catch panics and perform cleanup actions:
defer func() { if r := recover(); r != nil { // Recover from panic and perform necessary actions } }
The above is the detailed content of When and How Can Defer Statements Be Used in Go?. For more information, please follow other related articles on the PHP Chinese website!