gpt4 book ai didi

go - 接受 channel 和 slice 的通用函数

转载 作者:行者123 更新时间:2023-12-02 01:25:51 25 4
gpt4 key购买 nike

我正在尝试在 Golang 中编写通用函数,该函数将以类似的方式在 slice 和 channel 中搜索值。这是一个例子:

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

但我收到以下编译错误:无法范围输入(受 chan int|[]int 约束的 T 类型变量)(T 没有核心类型)

我尝试创建通用界面,如下所示:

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(T 类型的变量受 Rangable 约束)(T 没有核心类型),但它基本保持不变...

有什么方法可以使用泛型或 channel 来解决此任务,并且 slice 无法“转换”为相同的核心类型吗?

感谢您的任何建议和想法!

最佳答案

你不能这样做。

range 表达式必须一个核心类型作为开始。具有不同类型术语的联合没有核心类型,因为没有一个共同的基础类型。

您还可以直观地了解为什么 range 需要核心类型: slice 和 channel 范围的语义不同。

  1. 在 channel 上进行测距可能是阻塞操作,在 slice 上进行测距则不是

  2. 迭代变量不同

for i, item := range someSlice {}

对于 slice ,iint 类型的索引,item 是 slice 元素的类型。

for item := range someChan {}

对于 channel ,item 是 chan 元素的类型,也是唯一可能的范围变量。

你能拥有的最好的就是类型开关:

func MinOf[T any, U chan T | []T](input U) (result int) {
switch t := any(input).(type) {
case chan T:
// range over chan
case []T:
// range over slice
}
return
}

但同样,该函数的行为(阻塞与非阻塞)取决于类型,并且不清楚在这里使用泛型可以获得什么优势。

关于go - 接受 channel 和 slice 的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74674257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com