-2

Coming from years of Java, I recently picked up Golang and I wondered how the somewhat different paradigm affects common practices. Most importantly: If I define a struct and I want to have a function which works on that struct (aka a method), do I define the function as "belonging" to the struct or do I rather pass the pointer to that struct in an own function body? In other terms:

func (c *Component) initState()

or

func initState(c *Component)

Does either one have advantage over the other (other than e.g. readability for Java users or semantic clarity), as there are no real object/class concepts in Golang? I'd mostly go for the first alternative, but my view may be biased by working in an object-oriented world for some time, that's why I'm asking.

kopaka
  • 535
  • 4
  • 17
  • 2
    Methods allow you to implement interfaces, functions don't. – mkopriva Jun 25 '20 at 14:56
  • 2
    The first defines a "method" and the second is a "function" and not a method! Methods allow a type to satisfy interfaces, functions don't. – Volker Jun 25 '20 at 14:57
  • 1
    One potentially useful side effect of methods is that, since they are bound to the receiver's type, it is easier to avoid naming collision. For example you can have `func (T1) F()` and `func (T2) F()` in the same package, while `func F(T1)` and `func F(T2)` in the same package will cause a compiler error. – mkopriva Jun 25 '20 at 15:08

1 Answers1

1

The difference is mostly semantic: is initState a behavior of Component, or is it a function operating on Component?

There is one syntactic difference, and that is that only a method (a function with a receiver) can satisfy an interface. If that is not relevant to your case, then follow the semantic distinction.

Adrian
  • 42,911
  • 6
  • 107
  • 99