泛型范围覆盖映射的并集。

huangapple go评论144阅读模式
英文:

Generics range over union of maps

问题

以下是使用泛型的简单示例,我们想要复制一个映射:

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))
}

这段代码在编译时出错,返回以下错误信息:

./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)

如何绕过这个问题,并使得map[string]intmap[string]float64类型的copyMap函数正常工作?

英文:

There is a simple example of use of generics in which we want to copy a 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))
}

demo here

This code fails to compile returning error

./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)

How can I circumvent this issue and have a working generic copyMap function working for types map[string]int and map[string]float64?

答案1

得分: 1

你好!以下是翻译好的内容:

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

demo


或者,正如 @jubObs 提到的那样,可以使用 https://cs.opensource.google/go/x/exp/+/062eb4c6:maps/maps.go;l=65(使用了类似的结构)。


希望对你有帮助!如果还有其他问题,请随时提问。

<details>
<summary>英文:</summary>

Do 

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

[demo][1]

------

Or indeed just use https://cs.opensource.google/go/x/exp/+/062eb4c6:maps/maps.go;l=65 (who uses a similar construct) as @jubObs mentioned.

  [1]: https://go.dev/play/p/AwvDGkcAoEK

</details>



huangapple
  • 本文由 发表于 2023年2月13日 22:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定