Why is the slice sometimes passed by reference, sometimes by pointer?

In the default container/heap package in go, there's an example for implementing a priority queue.

While looking at the sample code, it uses a slice []*Item, and implements the heap.Interface.

My trouble is with the following bit. Why are some functions declared with the priority queue as a slice and sometimes as a pointer to slice ?:

func (pq PriorityQueue) Swap(i, j int) {...}
// vs
func (pq *PriorityQueue) Push(x interface{}) {...}

Why isn't it always (pq PriorityQueue) ? On this other StackOverflow thread about pointer to slices, the docs say that slices are refence types, so why use pointers on them ? I'm having trouble with the fact that the official doc says something then mixes both without explaining the point of adding a pointer.

Thanks for your insights !

EDIT: Here's an example:

// original sample code from the docs:
func (pq *PriorityQueue) Push(x interface{}) {
    n := len(*pq)
    item := x.(*Item)
    item.index = n
    *pq = append(*pq, item)

// is this the same (removed pointers to slice) ?
func (pq PriorityQueue) Push(x interface{}) {
    n := len(pq)
    item := x.(*Item)
    item.index = n
    pq = append(pq, item)

If both functions are the same, why use a pointer now ?


This article on the Go blog explains why.

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 to pass a pointer 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


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

Need Your Help

Scope private classes in a separate file

javascript oop

Is there a way to create a private class in a separate file without polluting the global namespace? Currently I just create a sub-namespace and put all of the private classes that other public clas...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.