I have no idea where to post this question since it isn't about the Go language specification itself but rather the justification.

In the Go language, functions can have receiver parameters to achieve an extension-method-like syntax feature. However, only types declared within the same package are allowed as type of a receiver.

func (a int) add(b int) int { // doesn't compile
    return a + b

type Int int
func (a Int) add(b Int) Int { // compiles
    return a + b

This seems like a completely arbitrary restriction to me wich forces the programmer to declare type aliases for the same type in every module just to create extension methods. Is there any justification at all for this part of the language specification? All arguments aside from "just because" would suffice. I understand that Go aims to be a simple language, hence I really can't get my head around why the language designers would make this decision.


The main reason I can think of is it would simplify and speed up compiling, especially incremental compiling, because the entire type definition is within one file. Go trades off features in favor of compiler simplicity much more frequently than other languages its age.

  • 2
    Within one package, not one file. The compilation unit is one package, which has one or more files. – peterSO Dec 12 '19 at 13:27
  • I don't know the compiler details obviously, but creating a type alias for another type just defers the resolution of an external type, doesn't it? The compiler won't be able to create a full signature without looking up information for the int type so why go that extra step with type aliasing? – Niklas Vest Dec 13 '19 at 12:43
  • It also avoids dealing with the potential of shadowing the original method. – Dolanor Feb 24 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.