Go语言 Map并集上的泛型范围

0ve6wy6x  于 2023-02-17  发布在  Go
关注(0)|答案(1)|浏览(124)

有一个使用泛型的简单示例,我们希望在其中复制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]intmap[string]float64类型呢?

ilmyapht

ilmyapht1#

func copyMap[T ~map[string]V, V any](m T) T {/* ... */}

demo
或者实际上只是使用https://cs.opensource.google/go/x/exp/+/062eb4c6:maps/maps.go;l=65(使用类似的结构),如@jubObs所提到的。

相关问题