英文:
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]int
和map[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 {/* ... */}
或者,正如 @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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论