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?

huangapple go评论71阅读模式
英文:

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{}

// 这是允许的
func (*A) foo(){}
func (*B) foo(){}

// 这是不允许的
func foo(*A){}
func foo(*B){} // 编译错误:"foo在此块中重新声明"

这个选择背后的逻辑是什么?

英文:

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?

答案1

得分: 3

禁止具有相同名称但不同类型的具体类型的方法,在Go中是为了简化方法调度。其他语言的经验告诉我们,具有相同名称但不同签名的各种方法有时很有用,但在实践中可能会令人困惑和脆弱。在Go的类型系统中,只通过名称匹配并要求类型一致是一个重要的简化决策。

至于运算符重载,它似乎更多是一种方便而不是绝对要求。再次强调,没有运算符重载会使事情更简单。

允许具有相同名称但不同类型的方法(可选地具有相同的参数类型,在同一个包中声明)是有明显原因的:将方法绑定到类型自然地为方法提供了一个“命名空间”,即它们所属的类型。

如果不允许这样做,你将无法在同一个包中声明实现相同接口的多个类型。这将需要将它们放入不同的包中。

英文:

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.

huangapple
  • 本文由 发表于 2022年2月20日 17:00:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/71192845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定