Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of defining Go methods away from struct definitions?

Tags:

struct

go

Go allows one to define methods separately from the struct/datatype they work on. Does it mean just flexibility in placing the method definitions or something more?

I've heard Go's struct/methods system being compared to monkey patching, but if I understand correctly, then you really can't add methods to any existing type (struct), as methods must reside in same package as the type. Ie. you can monkey patch only the types which are under your control anyway. Or am I missing something?

In which cases would you define a type and its methods in separate source files (or in different parts of the same source file)?

like image 459
Aivar Avatar asked Oct 16 '12 10:10

Aivar


1 Answers

This is an advantage of Go over type based languages : you can organize your files as you like :

  • you can put all the similar functions together, even if there are many receiver types
  • you can split a file which would otherwise be too big

As frequently, Go didn't add a constraint which was useless. So the answer could also be "why not" ?

you really can't add methods to any existing type (struct), as methods must reside in same package as the type

If you could, you might not be able to determine which function to call in case of the same function name used on the same struct in two different packages. Or that would make certain packages incompatible.

like image 163
Denys Séguret Avatar answered Oct 26 '22 11:10

Denys Séguret