doufeng3602 2016-01-28 07: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 07: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部