Where are closure storing the captured variables ?

152 views
Skip to first unread message

chris...@meessen.net

unread,
Jul 5, 2023, 8:35:52 PM7/5/23
to golang-nuts
Hello,

Closure need space to store the captured variables. According to runtime.MemStats, it is not on the heap. Where are these variable stored ? On the stack ?

Axel Wagner

unread,
Jul 6, 2023, 2:23:39 AM7/6/23
to chris...@meessen.net, golang-nuts
It depends a bit on escape analysis. I think the easiest way to reason about it is to say that they are stored in the `func` value. If the `func` value escapes, than so do the closed-over variables. If it doesn't (and the closed-over variables are not otherwise escaped) they don't. At least to an approximation.

The precise details of how closures are implemented are described in this document: https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub
I don't think anything material has changed since then.

On Thu, Jul 6, 2023 at 2:35 AM chris...@meessen.net <chris...@meessen.net> wrote:
Hello,

Closure need space to store the captured variables. According to runtime.MemStats, it is not on the heap. Where are these variable stored ? On the stack ?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/dd7074fc-670d-4bb3-9b88-51af65d23d45n%40googlegroups.com.

jake...@gmail.com

unread,
Jul 6, 2023, 11:33:32 AM7/6/23
to golang-nuts
In addition to Axel's useful info, whenever you are interested in what escapes to the 'heap', it  can be helpful to build with escape analyses output. Try using "go build  -gcflags=-m".
Reply all
Reply to author
Forward
0 new messages