How does Go's compiler handle nested functions?

WBOY
Release: 2024-02-05 21:39:13
forward
1229 people have browsed it

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)
}
Copy after login

Is this function compiled as follows?

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

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template