GoLang : Closure program

Hi Friends,

Here is a sample closure program. A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

package main

import "fmt"

func closureFunc() func() int {
       fmt.Println("init the x ")
       x := 1
       return func() int {
              x++
              return x
       }
}

func normalFunc() int {
       x := 100
       x++
       return x
}

func main() {
       increment := closureFunc()
       fmt.Println(increment())
       fmt.Println(increment())
       num := normalFunc()
       fmt.Println(num)
       increment1 := closureFunc()
       fmt.Println(increment1())
       fmt.Println(increment1())
       fmt.Println(increment())
}

/*
closure helps us limit the scope of variables used by multiple functions
without closure, for two or more funcs to have access to the same variable,
that variable would need to be package scope
*/

 

 

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