Home >Backend Development >Golang >How does Go's compiler handle nested functions?

How does Go's compiler handle nested functions?

WBOY
WBOYforward
2024-02-05 21:39:131252browse

Go 的编译器如何处理嵌套函数?

Question content

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?


Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete