Home > Back-end >  Golang closure access variables outside of closure
Golang closure access variables outside of closure

Time:08-01

In the following code which uses closure, variable m and n are on stack or heap?

func main() {
    var m, n int

    add := func() int {
        return m   n
    }

    fmt.Println(add())
}


CodePudding user response:

You can build your code with following flags:

go build -gcflags="-m"

and see what is actually happening. In this particular case for the whole file:

package main

import "fmt"

func main() {
    var m, n int

    add := func() int {
        return m   n
    }

    fmt.Println(add())
}

the output is as follows (go version go1.18 darwin/arm64):

./main.go:8:9: can inline main.func1
./main.go:12:17: inlining call to main.func1
./main.go:12:13: inlining call to fmt.Println
./main.go:8:9: func literal does not escape
./main.go:12:13: ... argument does not escape
./main.go:12:17: ~R0 escapes to heap

So m and n don't escape to heap, but the result of calling add does escape.

  • Related