我使用Go的heap包創建優先級隊列。文檔中有一個an example。Go堆。作爲結構的接口
我創建的隊列需要基於結構而不是切片,因爲它需要其他屬性(如互斥鎖)。
type PQueue struct {
queue []*Item
sync.Mutex
}
我執行heap.Interface要求的所有方法。
問題是我的PQueue.Push
方法似乎不會永久性地爲PQueue.queue
添加值。
func (p PQueue) Push(x interface{}) {
p.Lock()
defer p.Unlock()
item := x.(*Item)
item.place = len(p.queue) // the index of an item in the queue
p.queue = append(p.queue, item)
// len(p.queue) does increase
// after the functions exits, the queues length has not increased
}
如果我打印在這個函數結束時的p.queue
長度,該長度增加了。然而,函數退出後,似乎原來的結構不會被更新。
我認爲這可能是因爲func (p PQueue)
不是指針而發生的。爲什麼會這樣?有沒有辦法解決它?如果我使用func (p *PQeueue) Push(x interface{})
代替,我需要實現我自己的堆,因爲heap.Interface
明確地不需要指針。這是我唯一的選擇嗎?
那麼,heap.Interface'不需要指針。指針類型可以實現一個接口('* os.File'是一個'io.Reader')。嘗試一下,如果它無法解決問題,請發表另一個問題;有人會試圖幫助解決它。 – twotwotwo