问题
type A struct {
x1 []int
x2 []string
}
func (this *A) Test() {
fmt.Printf("this is: %p, %+v\n", this, *this)
}
func main() {
var fn func()
{
a := &A{}
a.x1 = []int{1, 2, 3}
a.x2 = []string{"one", "two", "three"}
fn = a.Test
}
fn()
}
Please see: https://play.golang.org/p/YiwHG0b1hW-
My question is:
- Will 'a' be released out of {} local scope?
- Is the lifetime of 'a' equal to the one of 'fn'?
回答1:
Go is a garbage collected language. As long as you don't touch package unsafe
(or similar like Value.UnsafeAddr() in package reflect
), all values remain in memory as long as they are reachable. You don't have to worry about memory management.
That's why it's also safe to return addresses (pointers) of local variables created inside functions. And also it's safe to refer to local variables from function values (closures) that will be out of scope when the function value is executed some time in the future, like this one:
func counter() func() int {
i := 0
return func() int {
i++
return i
}
}
This counter()
returns a function (closure) which when called, returns increasing values:
c := counter()
fmt.Println(c())
fmt.Println(c())
fmt.Println(c())
This outputs (try it on the Go Playground):
1
2
3
counter()
creates a local variable i
which is not returned, but is accessed from the function value returned by it. As long as the returned function value is accessible, the local variable i
is not freed. Also if you call counter()
again, that creates a new i
variable distinct from the previous one.
See related questions:
How to delete struct object in go?
Cannot free memory once occupied by bytes.Buffer
来源:https://stackoverflow.com/questions/59211106/is-there-any-problem-if-i-hold-a-member-function-pointer-out-of-the-pointer-inst