Go 是否支持 map 和 slice 等内置类型的运算符重载?
Does Go support operator overloading for builtin types like map and slice?
在python中,我可以通过定义__getitem__()
来定义覆盖列表项访问和字典值访问的类型。我可以在 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?
您可以使用 map
类型来做类似的事情。这是例子。
type MyItem struct {
name string
}
type MySlice map[int]MyItem
func (m MySlice) getItem(i int) MyItem {
return m[i]
}
func (m MySlice) setItem(i int, item MyItem) {
m[i] = item
}
func main() {
var items = MySlice{}
items.setItem(0, MyItem{"john"})
items[1] = MyItem{"doe"}
var item0 = items[0]
fmt.Println(item0.name)
var item1 = items.getItem(1)
fmt.Println(item1.name)
}
正如我们所见,设置和获取item0
和item1
的方式不同,但结果是一样的。
// set data
items.setItem(0, item)
items[0] = item
// get data
item = items[0]
item = items.getItem(0)
不,运算符重载不是 Go 的特性。
引用 official FAQ 来解释 为什么 :
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.
在python中,我可以通过定义__getitem__()
来定义覆盖列表项访问和字典值访问的类型。我可以在 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?
您可以使用 map
类型来做类似的事情。这是例子。
type MyItem struct {
name string
}
type MySlice map[int]MyItem
func (m MySlice) getItem(i int) MyItem {
return m[i]
}
func (m MySlice) setItem(i int, item MyItem) {
m[i] = item
}
func main() {
var items = MySlice{}
items.setItem(0, MyItem{"john"})
items[1] = MyItem{"doe"}
var item0 = items[0]
fmt.Println(item0.name)
var item1 = items.getItem(1)
fmt.Println(item1.name)
}
正如我们所见,设置和获取item0
和item1
的方式不同,但结果是一样的。
// set data
items.setItem(0, item)
items[0] = item
// get data
item = items[0]
item = items.getItem(0)
不,运算符重载不是 Go 的特性。
引用 official FAQ 来解释 为什么 :
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.