Golang: The easy example of Go deferred function


Deferred function means that the function call is deferred after/until the surrounding function   done / returns.

Here is the basic and easy sample of defer uses in Golang (code):


package main

import "fmt"

var (
	a = 10
	b = 2
	c = 0
)

func multiply(aa int, bb int, c *int) {
	*c = aa * bb
	fmt.Printf("2. value of c: %v ", *c) // Print pointer value
}

func main() {
	defer multiply(a, b, &c) // Will be executed after main() finished

	fmt.Printf("1. value of c: %d \n", c)

}

Output:

1. value of c: 0 
2. value of c: 20 
Program exited.

Another Example about defer


package main

import "fmt"

func main() {
	defer fmt.Println("1")
	defer fmt.Println("2")
	defer fmt.Println("3")
	defer fmt.Println("4")
}

Output:

4
3
2
1

Deferred function calls are executed in Last In First Out order after the surrounding function returns.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s