pointer receiver basic question

62 views
Skip to first unread message

Robert Solomon

unread,
Jul 23, 2020, 8:27:03 PM7/23/20
to golang-nuts
Hi.  I'm going thru the example code for container/heap.  In the documentation is this example:

func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]   // my question is about this line.
return x
}

Why does the last assignment have to assign to a dereferenced pointer, ie, *h = old[0 : n-1]?
Why does it not work if the last assignment is written as old = old[0 : n-1]?  I know this does not work because I tried it.

Thanks for your attention.

Ian Lance Taylor

unread,
Jul 23, 2020, 10:37:12 PM7/23/20
to Robert Solomon, golang-nuts
I'm not quite sure how to answer this question because there seems to
be some sort of deep misunderstanding here.

"old" is a local variable in the IntHeap.Pop method. Changing old, as
with "old = old[0 : n-1]", isn't going to affect the heap at all. It
will just change a local variable that will go away when the method
returns.

Ian
Reply all
Reply to author
Forward
0 new messages