指针接收器 vs 值接收器

huangapple go评论79阅读模式
英文:

pointer receiver vs value receiver

问题

情况:

我了解了指针接收器值接收器。据我所知:如果你想修改对象本身,你需要使用指针接收器。我在阅读关于接口的更多内容时,在Go文档中找到了这段代码:

type Sequence []int

// Methods required by sort.Interface.
func (s Sequence) Len() int {
    return len(s)
}
func (s Sequence) Less(i, j int) bool {
    return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
  • LessLen 方法使用的是值接收器,这是有道理的,因为它们返回数据而不是修改 Sequence 的状态。

  • 但在 Swap 的例子中,我很好奇为什么它仍然使用值接收器,看起来它似乎是在尝试修改它的状态。

问题:

这是一个错误吗,还是我的值/指针接收器的理解有误?

英文:

Situation:

I've learned about pointer receivers and value receivers. From what I understand: if you want to modify the object itself, you need to use a pointer receiver. I was reading more about interfaces in the go documentation and found this chunk of code:

type Sequence []int

// Methods required by sort.Interface.
func (s Sequence) Len() int {
    return len(s)
}
func (s Sequence) Less(i, j int) bool {
    return s[i] &lt; s[j]
}
func (s Sequence) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
  • The Less and Len methods are using value receivers and this makes sense, because they are returning data and not modifying the Sequence state.

  • But in the Swap example, I am curious why it is still using a value receiver when it looks like it is trying to modify its state.

Question:

Is this a mistake, or is my understanding of value/pointer receivers flawed in some way?

答案1

得分: 3

稍微解释一下@squiguy的评论,切片对象的值本身是对底层数组的引用,包括指向切片开始位置的数组元素的指针、切片的长度以及切片的容量(从切片开始位置到数组末尾的元素数量)。当你将一个切片传递给一个函数时,传递的是上述信息的值,所以函数内部的切片仍然引用同一个底层数组。这就是为什么Swap函数能够交换切片中的元素,即使切片本身是按值传递的原因。

英文:

To expand a bit on @squiguy's comment, the value of a slice object is itself a reference to an underlying array, including a pointer to the element in the array at which the slice begins, the length of the slice, and the slice's capacity (the number of elements in the underlying array from the beginning of the slice to the end of the array). When you pass a slice to a function, it is the above information that is passed by value, so the slice within the function still refers to the same underlying array. This is how Swap is able to swap elements in the slice even though the slice itself is passed by value.

huangapple
  • 本文由 发表于 2017年1月21日 01:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/41768993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定