When writing nested functions in go, how does the compiler handle it? Does it become another function and placed outside the code, or is it recreated when 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 does it compile exactly as written, meaning that every time funca
is called new memory is allocated for funcb
's definition?
Nested functions are compiled once.
Since FuncB does not close variables in the surrounding scope, FuncA does not allocate heap memory.
If FuncB closes any variables in the surrounding scope, then those variables will be allocated on the heap. The function itself is compiled once.
The above is the detailed content of How does Go's compiler handle nested functions?. For more information, please follow other related articles on the PHP Chinese website!