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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀