【发布时间】:2015-05-07 12:00:27
【问题描述】:
在 go 中默认的 container/heap 包中,有一个实现优先级队列的示例。
在查看the sample code时,它使用了一个切片[]*Item,并实现了heap.Interface。
我的麻烦在于以下几点。为什么有些函数将优先级队列声明为切片,有时声明为切片指针?:
func (pq PriorityQueue) Swap(i, j int) {...}
// vs
func (pq *PriorityQueue) Push(x interface{}) {...}
为什么不总是 (pq PriorityQueue) ?在另一个StackOverflow thread about pointer to slices 上,文档说切片是引用类型,那么为什么要在它们上使用指针呢?我遇到了这样一个事实,即官方文档说了一些话,然后将两者混合在一起,而没有解释添加指针的意义。
感谢您的见解!
编辑: 这是一个例子:
// 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)
}
如果两个函数相同,为什么现在使用指针?
【问题讨论】: