DEV Community

Arthur Christoph
Arthur Christoph

Posted on

Go Series: Closure

Golang Logo

A closure is the combination of a function and the lexical environment within which that function was declared.
This environment consists of any local variables that were in-scope at the time the closure was created.
The closure concept exists in many languages, in JS for example , it is heavily used for many cases. In go, closure is commonly used for defer and goroutines - we'll explore more of these topics in upcoming series.

The function adder returns another function when invoked, the lexical scope includes the sum variable which is accessible by the returned function. Note that in Go, a closure is always an anonymous function.

func adder() func(int) int {
   sum := 0
  // this is a closure, it has access to sum variable
  // each closure has its own sum variable
    return func(x int) int {
        sum += x
        return sum
    }
}

Enter fullscreen mode Exit fullscreen mode

every time adder is invoked, it creates a new function with closure.

  addFn := adder()
  fmt.Println(addFn(1)) // initial sum value of 0 is added to 1  
  fmt.Println(addFn(2)) // returns 3, sum variable is maintained by addFn closure
  // calling adder like below will not work as intended as the closure from first line is not being used by the second line, instead, creating a new one
  fmt.Println(adder()(1)) // returns 1
  fmt.Println(adder()(100)) // returns 100
Enter fullscreen mode Exit fullscreen mode

Another example of closure below where the closure is assigned to a variable first

func namer() func() string {
    name := "my name"
  // name variable still exists in fn even after namer is finished
    fn := func() string {
        return name
    }
  return fn
}
Enter fullscreen mode Exit fullscreen mode

With the fundamental understanding of closure, let's explore defer in the next post - one of the unique things in Go compared to other popular languages

Top comments (0)