doufeng3602 2016-01-28 15:14
浏览 22
已采纳

这两个Go代码段是否等效?

Having this struct

type Square struct {
    Side int
}

Are these to functions equivalent?

func (s *Square) SetSide(side int) {
    s.Side = side
}

vs

func SetSquareSide(s *Square, side int) {
    s.Side = side
}

I know they do the same, but are they really equivalent? I mean, is there any internal difference or something?

Try online: https://play.golang.org/p/gpt2KmsVrz

  • 写回答

2条回答 默认 最新

  • dongxiji0687 2016-01-28 15:54
    关注

    These "function" the same way, and in reality they are called in nearly the same way. The method is called as a method expression, with the receiver as the first argument:

    var s Square
    
    // The method call
    s.SetSide(5)
    // is equivalent to the method expression
    (*Square).SetSide(&s, 5)
    

    The SetSide method can also be used as a method value to satisfy the function signature func(int), where as the SetSquareSide cannot.

    var f func(int)
    
    f = a.SetSide
    f(9)
    

    This is on top of the obvious fact that the method set of Square satisfies the interface

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

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换