gpt4 book ai didi

linq - Go 泛型是否允许 LINQ to Objects 等效?

转载 作者:行者123 更新时间:2023-12-05 01:52:45 24 4
gpt4 key购买 nike

随着addition of generics in Go 1.18 , 现在是否有可能提出与 C# 的 LINQ to Objects 等效的东西? ?

或者与 C# 泛型相比,Go 的泛型在原则上是否缺少某些东西,这将使这变得困难或不可能?

比如原来的第一个101 LINQ samples ("LowNumbers") 现在可以在 Go 中使用泛型实现,大致如下:

package main

import (
"fmt"
)

type collection[T comparable] []T

func (input collection[T]) where(pred func(T) bool) collection[T] {
result := collection[T]{}
for _, j := range input {
if pred(j) {
result = append(result, j)
}
}
return result
}

func main() {
numbers := collection[int]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
lowNums := numbers.where(func(i int) bool { return i < 5 })
fmt.Println("Numbers < 5:")
fmt.Println(lowNums)
}

最佳答案

是也不是。

几乎可以使用链式 API 到达那里。这适用于许多标准的 LINQ 方法,例如 SkipTakeWhereFirst最后

当您需要在流程/流中切换到另一种通用类型时,不起作用。

Go Generics 不允许方法 有除定义它们的接口(interface)/结构之外的其他类型参数。例如你不能有一个结构 Foo[T any] 然后有一个方法 Bar[O any]这对于像 Select 这样的方法是必需的,其中您有一种输入类型和另一种输出类型。

但是,如果您不使用链接而只使用普通函数。那么您可以获得非常接近的功能。

我在这里做到了:https://github.com/asynkron/gofun

这是一个通过模拟协程实现的完全懒惰的可枚举实现。

这里不起作用的是像 Zip 这样的函数,它需要同时枚举两个可枚举对象。 (虽然有办法破解它。但没什么好看的)

关于linq - Go 泛型是否允许 LINQ to Objects 等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71462116/

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