Pointer and slice reference type - receiver

See this article on the Go blog. It explains in detail what is happening and fully answers your question.

From the section Passing slices to functions:

It's important to understand that even though a slice contains a pointer, it is itself a value. Under the covers, it is a struct value holding a pointer and a length. It is not a pointer to a struct.

As a result you either need a pointer receiver or you need to return the slice as a value if you want to modify it with append.

If you just want to modify the contents of a slice you can simply pass the slice by value:

Even though the slice header is passed by value, the header includes a pointer to elements of an array, so both the original slice header and the copy of the header passed to the function describe the same array. Therefore, when the function returns, the modified elements can be seen through the original slice variable.

With append you are modifying the slice header. And

Thus if we want to write a function that modifies the header, we must return it as a result parameter

Or:

Another way to have a function modify the slice header is to pass a pointer to it.

You also seem to have a confusion on the use of pointers. See the spec:

For an operand x of type T, the address operation &x generates a pointer of type *T to x.

And:

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x.

Thus your example *stack = append(*stack, x) doesn't mean that you are passing a pointer to append, quite the opposite - you are dereferencing the pointer to pass the value it's pointing to.


The problem you are having is that append returns a reference to the new slice. You cannot change the value of the function's receiver unless it is a pointer.

What I would recommend rather is making a wrapper struct:

type Stack struct{
   data []interface{}
   size int
}
func (s *Stack) Push(i interface{}){
   s.data = append(s.data,i)
   s.size++
}

Tags:

Go