我正在try 用Golang编写泛型函数,以类似的方式在切片和通道中搜索值.下面是一个例子:
// MinOf returns the smallest number found among the channel / slice contents
func MinOf[T chan int | []int](input T) (result int) {
for _, value := range input {
if result > value {
result = value
}
}
return
}
但我得到以下编译错误:cannot range over input (variable of type T constrained by chan int|[]int) (T has no core type)
.
我曾try 创建通用界面,如下所示:
type Rangable interface {
chan int | []int
}
// MinOf returns the smallest number found among the channel / slice contents
func MinOf[T Rangable](input T) (result int) {
for _, value := range input {
if result > value {
result = value
}
}
return
}
虽然,误差已更改为cannot range over input (variable of type T constrained by Rangable) (T has no core type)
,但基本保持不变...
有没有办法使用泛型或通道和切片不能"强制转换"为相同的核心类型来解决此任务?
感谢您的任何建议和 idea !