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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟