will golang closure memory leak?

Issue

let’s say i have this closure func

package main

type A struct {
    Name string
}

func main() {
    s := func(name string) *A {
        return &A{
            Name: name,
        }
    }("checkmate")

    s.Name = "bbb"
}

i have tested with benchmark and gcflags and this is the result

cpu: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
BenchmarkMain-4         1000000000               0.4877 ns/op          0 B/op          0 allocs/op

go build -gcflags "-m"

./main.go:8:7: can inline main.func1
./main.go:7:6: can inline main
./main.go:12:3: inlining call to main.func1
./main.go:12:3: &A{...} does not escape

is this still memory safe? or maybe there’s something missing for my memory allocation check?

Solution

No, closures do not leak memory.

Answered By – Volker

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.