Defer statement in Go
The defer statement is used to schedule a function call to be executed when the surrounding function returns. The deferred function calls are executed in LIFO order, meaning that the last deferred function called will be the first to run.
Here's an example of using the defer statement:
func doSomething() {
defer fmt.Println("done")
fmt.Println("doing something")
}
doSomething() // prints "doing something" followed by "done"
In this example, we define a function that prints a message and then schedules a deferred function call to print another message. When we call the doSomething function, the message "doing something" is printed first, followed by the message "done" which was scheduled to run when the function returns.
The defer statement is useful for ensuring that certain cleanup tasks are performed when a function returns, regardless of how it returns.
No comments:
Post a Comment