NeoWang
NeoWang

Reputation: 18533

Does Go support operator overloading for builtin types like map and slice?

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?

Upvotes: 2

Views: 3542

Answers (1)

AndrewN
AndrewN

Reputation: 425

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.

Upvotes: 9

Related Questions