有一个使用泛型的简单示例,我们希望在其中复制Map
package main
import "fmt"
type myMap interface {
map[string]int | map[string]float64
}
func copyMap[T myMap](m T) T {
newMap := make(T)
for key, elem := range m {
newMap[key] = elem
}
return newMap
}
func main() {
m := map[string]int{"seven": 7}
fmt.Println(copyMap(m))
}
演示here
此代码编译失败,返回错误
./prog.go:12:17: invalid argument: cannot make T: no core type
./prog.go:13:25: cannot range over m (variable of type T constrained by myMap) (T has no core type)
./prog.go:14:18: invalid operation: cannot index m (variable of type T constrained by myMap)
我怎样才能避免这个问题,并让一个通用的copyMap函数适用于map[string]int
和map[string]float64
类型呢?
1条答案
按热度按时间ilmyapht1#
做
demo
或者实际上只是使用https://cs.opensource.google/go/x/exp/+/062eb4c6:maps/maps.go;l=65(使用类似的结构),如@jubObs所提到的。