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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)