Home > OS >  How does Go's compiler treat nested functions?
How does Go's compiler treat nested functions?

Time:11-28

When writing a nested function in Go, how does the compiler treat it? Is it turned into another function and put outside the code, or does it get re-created anytime the parent function is called?

For example:

func FuncA() int {
    a := 0
    funcB := func(_a int) int {
        return _a
    }
    return funcB(a)
}

Is this function compiled as follows?

func FuncA() int {
    a := 0
    return _funcB(a)
}
func _funcB(_a int) int {
    return _a
}

Or is it compiled exactly as written which means that new memory is allocated for the definition of funcB anytime FuncA is called?

CodePudding user response:

Nested functions are compiled once.

Because FuncB does not close over variables in the surrounding scope, FuncA does not allocate heap memory.

If FuncB closed over any variables in the surrounding scope, then those variables will be allocated on the heap. The function itself is compiled once.

CodePudding user response:

Nested functions are compiled once as closures. All the variables that the nested function uses from the enclosing scope are put on the heap, and passed to the nested function. In the following snippet:

 func FuncA() int {
    a := 0
    funcB := func() int {
        return a
    }
    return funcB()
}

The compiled code is equivalent to:

type closureB struct {
   a int
}

func FuncA() int {
  c:=new(closureB)
  c.a=0
  return funcB(c)
}

func funcB(c *closureB) int {
  return c.a
}

Exact details depend on the runtime and compiler implementation.

  •  Tags:  
  • go
  • Related