On Fri, Jul 24, 2020 at 4:25 PM burak serdar <
bse...@computer.org> wrote:
>
> On Fri, Jul 24, 2020 at 5:21 PM Ian Lance Taylor <
ia...@golang.org> wrote:
> >
> > On Fri, Jul 24, 2020 at 4:07 PM Tony Yang <
tony...@umich.edu> wrote:
> > >
> > > Hi Go community,
> > >
> > > I am wondering if a method with the pointer receiver keeps the receiver instance from garbage collected.
> > >
> > > To put the idea into a code example
> > >
> > > ```
> > > type counter struct {
> > > c int
> > > }
> > >
> > > func (c *counter) next() int {
> > > c.c = c.c + 1
> > > return c.c
> > > }
> > >
> > > func getNextFunc() func () int {
> > > // Question: will c be garbage collected after the function retruns?
> > > c := &counter{}
> > > return c.next
> > > }
> >
> > The mere existence of a pointer receiver does not prevent a value from
> > being garbage collected. In your example, if the counter value is
> > allocated on the heap in getNextFunc, that heap allocation can be
> > collected after getNextFunc returns (in practice in this example c
> > would be allocated on the stack, not the heap, anyhow).
>
>
> What is returned from the function is a method, though. Isn't that
> essentially a closure keeping a reference to c, and thus, c has to be
> allocated on the heap, and cannot be garbage collected until the
> returned function leaves the scope?
Yes, doing this will prevent c from garbage collected. Otherwise it