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
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 typeA
:
- a constant index must be in range
- if
x
is out of range at run time, a run-time panic occursa[x]
is the array element at indexx
and the type ofa[x]
is the element type ofA
For
a
of pointer to array type:
a[x]
is shorthand for(*a)[x]
For
a
of slice typeS
:
- if
x
is out of range at run time, a run-time panic occursa[x]
is the slice element at indexx
and the type ofa[x]
is the element type ofS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With