dsjpqpdm620596 2017-01-20 17:11
浏览 41
已采纳

指针接收器与值接收器

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] < 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条回答 默认 最新

  • dtpyvb1873 2017-01-20 18:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器