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)?
This is an advantage of Go over type based languages : you can organize your files as you like :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With