Search code examples
goclosures

In go, is it safe to store pointer of a local variable in global map?


I know that closure feature guarantees pointer of local variable returned from function can be used safely. But what if the pointer not be returned? For example, just save it in a global map:

type bigUnit struct {
    ...
}

var globalIndex = map[string]*bigUnit{}

func newBigUnit(id int, ...) {
    newOne := bigUnit{
        ...
    }
    globalIndex[id] = &newOne
}

Will the newOne be kept until the end of program?


Solution

  • newOne is an identifier local to your function newBigUnit and not accessible from the outside, so technically no. Also, since you can call newBigUnit multiple times, what would be the value?

    What you probably mean is whether the variable whose address is stored in the package-accessible map will be kept - yes, as long as you don't store something else or delete the entry it is accessible, so it will be kept.

    Generally the Go garbage collector guarantees that values will not be collected as long as they are accessible. If you want to know more about the Go garbage collector you could start with “A Guide to the Go Garbage Collector.”