For example, if I have some type A struct { B string; C int }
, and I have a func foo(a A) *string { return &a.B }
, and I call it with c := foo(a)
, will a
necessarily stay in context until c
is collectible?
Or, if I define func foo1(a A) *string { s := a.B; return &s }
will that have any effect on when the A
can be collected?
In the first example, assuming a
is not used after calling foo(a)
, a
is collectable, because you passed a
by value. The function returned a pointer to a value in a copy of a
, so a
becomes collectable, but the copy created in the function foo
is not collectable.
Now, if you passed &a
to foo(a *A)
, then a
would not be collectable, because c
is a pointer to it.
The second example you give also passes a copy of a
, so same arguments apply. However, if you passed &a
, and then returned a pointer to a copy a string from a
, a
would be collectible, but not the string you returned, because there is a reference to it.