Golang Closed Packet Analysis

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

In the programming language you've been exposed to, more or less has been exposed to closures.

So what's a closure?

Closures contain variables that are free (not bound to specific objects), are not defined within this block of code or in any global context, but are defined in the context in which the code block is defined (local variables). The word "closure" derives from the combination of the following: the code block to be executed (since free variables are contained in the code block, these free variables and the objects they refer to are not freed) and the computing Environment (scope) that provides the binding for free variables--from Baidu

Closures in the Golang

Implementing closures in Golang is a very simple thing, such as:


Let's analyze this closure, the function closure () is a function that does not need parameters, returns a type func (int) int type, in main (), we use a to receive the closure returned by the closure, which is equivalent to A is a func ( int) a function of type int, call a (5) on a, return the result with an X variable to receive, and then print the result.

If you have some memory of C, then you know that this notation in the closure () function is not allowed, because C is inside the function, the memory allocation is allocated on the stack, and the function closure () returns after this part of the stack space is invalidated; but in the go language, it works. Let's try to analyze why.

Follow GDB to see what the results are:

Use the command go build-gcflags "-n-l-M" closure

One of the closure is the one above the closure of the project, to see what important messages are printed:



What the? &x escapes to Heap??? No wonder we have no problem with the call to a function, Iers variable x flew into the heap, which means that the go language automatically recognizes this and allocates X's memory on the heap instead of on the stack of the function closure.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.