Home > Enterprise >  Why does Golang allow two functions to have the same name if they have different receiver types but
Why does Golang allow two functions to have the same name if they have different receiver types but

Time:02-23

Why does Golang allow two functions to have the same name if they have different receiver types but not if they have different parameter types? Consider for example

type A struct{}
type B struct{}

// This is allowed
func (*A) foo(){}
func (*B) foo(){}

// This is not allowed
func foo(*A){}
func foo(*B){} // compilation error: "foo redeclared in this block"

What is the logic behind this choice?

CodePudding user response:

Disallowing methods of a concrete type with same name and different types is in the Go FAQ: Why does Go not support overloading of methods and operators?

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.

Allowing methods with same name of different types (with optionally identical parameter types, declared in the same package) is allowed for obvious reasons: bounding methods to a type naturally gives the method a "name space", the type they belong to.

If it would not be allowed, you could not declare multiple types in the same package that would implement the same interface(s). That would require putting them into different packages.

  • Related