4 ms·
You can write your own LINQ in Go with a very short program. See https://github.com/nukata/linq-in-go https://github.com/nukata/linq-in-go for example. Here is
by suzuki 7y ago
You can write your own LINQ in Go with a very short program.
See https://github.com/nukata/linq-in-go https://github.com/nukata/linq-in-go for example.
Here is a self-contained excerpt:
type Any = interface{}
type Enumerator func(yield func(element Any))
// Select creates an Enumerator which applies f to each of elements.
func (loop Enumerator) Select(f func(Any) Any) Enumerator {
return func(yield func(Any)) {
loop(func(element Any) {
value := f(element)
yield(value)
})
}
}
// Range creates an Enumerator which counts from start
// up to start + count - 1.
func Range(start, count int) Enumerator {
end := start + count
return func(yield func(Any)) {
for i := start; i < end; i++ {
yield(i)
}
}
}
Now you can write the following:
squares := Range(1, 10).Select(func(x Any) Any { return x.(int) * x.(int) })
squares(func(num Any) {
Println(num)
})
// Output:
// 1
// 4
// 9
// 16
// 25
// 36
// 49
// 64
// 81
// 100
I'd say it is so elegant in Go!
- jadbox 7y agoIt's a little annoying though to be forced to use interface{} as type parameters for higher order list operations as there's a performance overhead when using it. Hopefully this is remedied when Go gets type generic support.
- whateveracct 7y agoNot to mention the complete lack of type safety (there are unsafe-style casts even in the example code.)
- suzuki 7y agoGood point! I'm looking forward to generics in Go.