英文:
Does Go support operator overloading for builtin types like map and slice?
问题
在Go语言中,你可以通过定义方法来实现类似的功能。你可以为自定义类型定义方法,以实现对切片元素和字典值的访问重载。下面是一个示例:
type MySlice []MyItem
func (s MySlice) getItem(i int) MyItem {
// 实现你的逻辑
}
// 使用重载后的访问方式
ms := MySlice{}
item := ms.getItem(0) // 调用ms.getItem(0)
通过定义getItem()
方法,你可以在自定义类型上实现对切片元素的访问重载。请根据你的需求在getItem()
方法中实现相应的逻辑。
英文:
In python, I can define types that override list item access and dict value access by defining __getitem__()
. Can I do something similar in Go?
// What I mean is:
type MySlice []MyItem
// Definition of MySlice
......
func (s MySlice) getItem(i int) MyItem {
}
......
// Access is overrided with calling getItem()
item := ms[0] //calling ms.getItem(0)
// Is this doable?
答案1
得分: 9
不,Go语言不支持运算符重载。
引用官方FAQ中的解释:
如果方法调度不需要进行类型匹配,那么方法调度就会变得简化。我们从其他语言的经验中得知,拥有相同名称但不同签名的多个方法有时会有用,但在实践中可能会令人困惑和脆弱。只通过名称匹配并要求类型一致是Go类型系统中的一个重要简化决策。
关于运算符重载,它似乎更多是一种便利而不是绝对要求。同样,没有运算符重载会使事情更简单。
英文:
No, operator overloading is not a feature of Go.
Quoting from the official FAQ to explain why:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论