首页 > 解决方案 > 为什么交换成员函数不需要使用指针?

问题描述

我是 Golang 的新手。当我尝试实现我的第一个 PriorityQueue 时,我发现 Push 和 Pop 函数需要使用成员的指针,而 Swap 不需要。

我知道如果您在成员函数中使用指针,这意味着您可以更改实例本身而不是其副本。但是为什么 Swap 可以使用副本而不是指针呢?

type maxHeap []int

func (max maxHeap) Len() int {
    return len(max)
}

func (max maxHeap) Less(a, b int) bool {
    return max[a] > max[b]
}

func (max maxHeap) Swap(a, b int) {
    max[a], max[b] = max[b], max[a]
}

func (max *maxHeap) Push(a interface{}) {
    *max = append(*max, a.(int))
}
func (max *maxHeap) Pop() interface{} {
    x := (*max)[len(*max)-1]
    *max = (*max)[0 : len(*max)-1]
    return x
}

标签: goheappriority-queue

解决方案


Try this as an exercise: write all the functions using a pointer receiver. In each function, grab the current value of the pointer at the top, to use until you need to change the value stored through the pointer.

So Swap and Push, respectively, become:

func (p *maxHeap) Swap(a, b int) {
    max := *p
    max[a], max[b] = max[b], max[a]
}
func (p *maxHeap) Push(a interface{}) {
    max := *p
    *p = append(max, a.(int))
}

Repeat for the other functions as needed.

Now, go back through each converted function. Which ones assign a new value to *p? Which functions never assign a new value and just keep using max?

When you answer this question, you should find yourself enlightened.

Side note: since Push immediately converts a to int, it probably should just take int. Likewise, Pop should just return int. Alternatively, well, see the standard container/heap package.


推荐阅读