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
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)
}
As far as I know they work the same way.
One difference is that only the first one could satisfy an interface specification.