这两段 Go 代码是否等价?

huangapple go评论65阅读模式
英文:

Are these two Go pieces of code equivalent?

问题

这两个函数是等价的,它们都用于设置 Square 结构体的 Side 字段。没有内部差异或其他特殊之处。

英文:

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

答案1

得分: 6

据我所知,它们的工作方式是相同的。

其中一个区别是只有第一个能够满足接口规范。

英文:

As far as I know they work the same way.

One difference is that only the first one could satisfy an interface specification.

答案2

得分: 3

这些"函数"的工作方式相同,在实际中它们以几乎相同的方式被调用。该方法被称为方法表达式,接收器作为第一个参数:

var s Square

// 方法调用
s.SetSide(5)
// 等同于方法表达式
(*Square).SetSide(&s, 5)

SetSide 方法也可以作为方法值用于满足函数签名 func(int),而 SetSquareSide 则不能。

var f func(int)

f = a.SetSide
f(9)

除此之外,显而易见的是 Square 的方法集满足接口

interface {
    SetSide(int)
}
英文:

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

huangapple
  • 本文由 发表于 2016年1月28日 23:14:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/35065179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定