Go Function Closure

Introduction

We can create functions inside of functions.

Let's move the add function inside of main:

package main/*from w  ww.j  a va  2 s  .  c  o  m*/

import "fmt" 

func main() { 
    add  := func(x, y int) int { 
        return x + y 
    } 
    fmt.Println(add(1,1)) 
} 

add is a local variable that has the type func(int, int) int.

It is a function that takes two int values and returns an int.

A local function has access to other local variables.

package main/*from   www .jav a 2  s. c o  m*/

import "fmt" 

func main() { 
    x  := 0 
    increment  := func() int { 
        x++ 
        return x 
    } 
    fmt.Println(increment()) 
    fmt.Println(increment()) 
} 

A function together with the nonlocal variables it references is known as a closure.

In this case, increment and the variable x form the closure.




PreviousNext

Related