为什么 Golang 允许两个具有不同接收者类型的函数具有相同的名称,但如果它们具有不同的参数类型则不允许?
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?
为什么Golang允许两个接收者类型不同但参数类型不同的函数重名?考虑例如
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"
这个选择背后的逻辑是什么?
不允许具有相同名称和不同类型的具体类型的方法在 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.
允许具有相同名称的不同类型的方法(具有可选的相同参数类型,在同一包中声明)是允许的,原因很明显:将方法绑定到一个类型自然会给方法一个“名称space” , 他们所属的类型。
如果不允许,则不能在实现相同接口的同一包中声明多个类型。那将需要将它们放入不同的包中。
为什么Golang允许两个接收者类型不同但参数类型不同的函数重名?考虑例如
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"
这个选择背后的逻辑是什么?
不允许具有相同名称和不同类型的具体类型的方法在 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.
允许具有相同名称的不同类型的方法(具有可选的相同参数类型,在同一包中声明)是允许的,原因很明显:将方法绑定到一个类型自然会给方法一个“名称space” , 他们所属的类型。
如果不允许,则不能在实现相同接口的同一包中声明多个类型。那将需要将它们放入不同的包中。