Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to slice and array

Tags:

arrays

slice

go

I was looking at Go's heap package's (https://golang.org/pkg/container/heap/) Priority Queue example and came across this:

type PriorityQueue []*Item
...
func (pq *PriorityQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    item.index = -1 // for safety
    *pq = old[0 : n-1]
    return item
} 

When I started playing around with this code to make sure I understood it, I tried:

item := *pq[0] // error

This gives you type *[]T does not support indexing. But if you do:

item := (*pq)[0] // all is well

This is type assertion right? Was hoping someone could explain what is going on here.

Here is some code to quickly show this: https://play.golang.org/p/uAzYASrm_Q

like image 794
khalieb Avatar asked Feb 08 '23 09:02

khalieb


1 Answers

What works for you is not type assertion - it's operation ordering.

The problem is rooted in the fact that the indexing precedes the dereferencing of your pointer. Once you put braces around the pointer dereferencing, it all works well, because the indexing is applied to the now dereferenced PriorityQueue instance.

You don't need to do that for array pointers, because they are automatically dereferenced - the slight difference between indexing arrays and slices is explained here: The Go Programming Language Specification - Index expressions

For a of array type A:

  • a constant index must be in range
  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the array element at index x and the type of a[x] is the element type of A

For a of pointer to array type:

  • a[x] is shorthand for (*a)[x]

For a of slice type S:

  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the slice element at index x and the type of a[x] is the element type of S
like image 159
Dimitar Dimitrov Avatar answered Feb 11 '23 00:02

Dimitar Dimitrov