简体   繁体   中英

Returning pointer on struct member or embedded struct in Go?

Taking address and returning pointer to a local variable inside a function in Go causes compiler to allocate it on heap rather than stack, so that returned pointer remains valid.

Now what happens if I take and return address of a struct member or embedded struct ?

type A struct {
    a,b,c int
}
type B struct {
    A
    d,e,f int
}
func (b *B) get1() *A {
    return &b.A
}
func (b *B) get2() *A {
    localB := B{}
    return &localB.A
}

Will compiler allocate embedded struct A on heap and keep members of B on stack ?

Will garbage collector collect localB even if localB.A reference is still in use ?

How can compiler determine when to keep embedded struct on stack or heap in case if it's accessed through reflection ?

Why are you even wondering about these details?

Quoting the Go FAQ (emphasis mine):

From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

and

In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.

The behavior of the compiler and the garbage collector are strictly implementation-dependent, and subject to changes across different releases. You cannot event prove your opening statement is always true: the compiler may decide to apply further optimization depending on how your function is written or invoked.

The compiler performs escape analysis to determine whether a variable may be used outside of the scope in which it is created, in which case it must be allocated on the heap. If the compiler can make sure that this won't happen, it allocates the variable on the stack.

However, this is the current behaviour of the compiler, but it is not mentioned in the specification, so it may change in any future version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM