Derek Parker

Random thoughts on programming.


Closures in Go

TL;DR Go implements closures by passing around a heap allocated struct which contains a function pointer and any closured variables.

 What are closures?

Closures, briefly, are functions that carry along with them variables declared within lexical scope of the defined function. So, what does this mean? Consider this:

package main

type generator func() int

func myFunc() generator {
        foo := 0
        return func() int {
                foo++
                return foo
         }
}

func main() {
        bar := myFunc()
        bar() // 1
        bar() // 2
}

The variable foo is in scope for the function that we declare and return from myFunc(). When we return our function, foo stays in scope, even though the function it was declared in has returned. How is this happening internally? To find out, lets look through some disassembled Go code!

Running go tool 6g -S foo.go provides

Continue reading →