简体   繁体   English

Golang指向切片和数组的指针

[英]Golang pointer to slice and array

I was looking at golang's heap package's ( https://golang.org/pkg/container/heap/ ) Priority Queue example and came across this: 我正在查看golang的堆包( https://golang.org/pkg/container/heap/)Priority Queue示例,并且遇到了这个:

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. 这给你类型* [] T不支持索引。 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 以下是一些快速显示的代码: 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. 一旦你在指针解除引用周围放置大括号,它一切正常,因为索引应用于现在解除引用的PriorityQueue实例。

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 您不需要为数组指针执行此操作,因为它们会自动解除引用 - 索引数组和切片之间的细微差别在此解释: Go编程语言规范 - 索引表达式

For a of array type A : 对于a阵列型的A

  • a constant index must be in range 常量索引必须在范围内
  • if x is out of range at run time, a run-time panic occurs 如果x在运行时超出范围,则会发生运行时混乱
  • a[x] is the array element at index x and the type of a[x] is the element type of A a[x]是索引x处的数组元素,而a[x]的类型是A的元素类型

For a of pointer to array type: 对于a指针数组类型:

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

For a of slice type S : 对于a切片类型的S

  • if x is out of range at run time, a run-time panic occurs 如果x在运行时超出范围,则会发生运行时混乱
  • a[x] is the slice element at index x and the type of a[x] is the element type of S a[x]是索引x处的切片元素,而a[x]的类型是S的元素类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM