dongmu2026 2014-04-02 18:13 采纳率: 100%
浏览 125
已采纳

为什么在为golang类型实现sort.Interface时不需要方法接收者是指针?

I am reading the docs for the sort stdlib package and the sample code reads like this:

type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

As I've learnt, function that mutate a type T needs to use *T as its method receiver. In the case of Len, Swap and Less why does it work ? Or am I misunderstanding the difference between using T vs *T as method receivers ?

  • 写回答

2条回答 默认 最新

  • douju4594 2014-04-03 07:14
    关注

    Go has three reference types:

    • map
    • slice
    • channel

    Every instance of these types holds a pointer to the actual data internally. This means that when you pass a value of one of these types the value is copied like every other value but the internal pointer still points to the same value.

    Quick example (run on play):

    func dumpFirst(s []int) {
        fmt.Printf("address of slice var: %p, address of element: %p
    ", &s, &s[0])
    }
    
    s1 := []int{1, 2, 3}
    s2 := s1
    
    dumpFirst(s1)
    dumpFirst(s2)
    

    will print something like:

    address of slice var: 0x1052e110, address of element: 0x1052e100
    address of slice var: 0x1052e120, address of element: 0x1052e100
    

    You can see: the address of the slice variable changes but the address of the first element in that slice remains the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘