‘defer’
statement is used to defer the execution of a function until the surrounding
function returns.
Syntax
defer
function
App.go
package main import "fmt" func main() { defer fmt.Println(", Welcome to Go Language") defer fmt.Print("Hello ") }
Output
Hello ,
Welcome to Go Language
When a
function returns, deferred calls are executed in LIFO (Last-In-First-Out)
order.
App.go
package main import "fmt" func main() { fmt.Println("Starting Execution") for i := 0; i < 10; i++ { defer fmt.Println(i) } defer fmt.Println("Finished Execution") }
Output
Starting
Execution
Finished
Execution
9
8
7
6
5
4
3
2
1
0
Note
a.
defer
statements are mainly used to clean the resources
b.
defer
will be called, even if there is an error in the code.
No comments:
Post a Comment