我正在 go 1.18 中测试泛型并查看了这个示例。我想重新创建该示例,但改为能够传入一片 int 或一片浮点数,而在函数中,我将对片中的所有内容求和。
这是我在迭代切片时遇到的一些问题。这是我试过的:
package main
import "fmt"
// NumberSlice constraint
type NumberSlice interface {
[]int64 | []float64
}
func add[N NumberSlice](n N) {
// want: to range over n and print value of v
for _, v := range n {
fmt.Println(v)
}
}
func main() {
ints := []int64{1, 2}
add(ints)
}
我得到了错误:
不能超过 n(N 类型的变量受 NumberSlice 约束)(N 没有核心类型)
我该如何做到这一点?
慕村225694
森栏