9

As a Go beginner, I stumbled across code where there are brackets directly after func

func (v Version) MarshalJSON() ([]byte, error) {
  return json.Marshal(v.String())
}

So what does (v Version) mean?

pogopaule
  • 1,533
  • 2
  • 10
  • 17

1 Answers1

14

This is not a function but a method. In this case, it adds the MarshalJSON method to the Version struct type.

The v is the name for the received value (and would be analogous to this in a Java method or self in Python), the Version specifies the type we're adding the method to.

See go by example for, well, an example, and the specification for more details.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • 3
    An important thing to note is that you can attach a function receiver to any type in go, it need not be a struct. – robbmj Sep 02 '15 at 19:57
  • 1
    Great! Thank you! I didn't yet make it to [methods in the go tour](http://tour.golang.org/methods/1) :-/ – pogopaule Sep 02 '15 at 19:59
  • @robbmj: Weirdest use of that I have seen yet is attaching a function to a function pointer. – Zan Lynx Sep 02 '15 at 21:05
  • @ZanLynx A good example of that would be attaching a `ServeHTTP` method on a custom function type so that it implements `http.Handler`. Not that weird at all! – elithrar Sep 02 '15 at 21:56
  • @elithrar: It starts to look like code obfuscation when you've got to dig through `f.ServeHTTP()`, `f()`, `f().PerformAction()`, etc. – Zan Lynx Sep 02 '15 at 22:00
  • That's a variable naming problem: if you're using short names beyond a short scope (i.e. a 10 line function) then it certainly becomes confusing! If that was (e.g.) `authHandler.ServeHTTP(w, r)` it'd be much clearer. I don't think that's an argument for *not* having methods on any types, though. – elithrar Sep 02 '15 at 22:05