mirror of
https://github.com/lightningnetwork/lnd.git
synced 2025-11-10 22:27:22 +01:00
In this commit, we introduce a new utility function `Collect` to the fn package. This function drains all elements from an iterator and returns them as a slice. This is particularly useful when transitioning from iterator-based APIs to code that expects slices, allowing for gradual migration to the new iterator patterns. The fn module's go.mod is also updated to require Go 1.23, which is necessary for the built-in iter.Seq type support. The replace directive will be removed once the fn package changes are merged and a new version is tagged.
30 lines
601 B
Go
30 lines
601 B
Go
package fn
|
|
|
|
import "iter"
|
|
|
|
// Collect drains all of the elements from the passed iterator, returning a
|
|
// slice of the contents.
|
|
func Collect[T any](seq iter.Seq[T]) []T {
|
|
|
|
var ret []T
|
|
for i := range seq {
|
|
ret = append(ret, i)
|
|
}
|
|
|
|
return ret
|
|
}
|
|
|
|
// CollectErr drains all of the elements from the passed iterator with error
|
|
// handling, returning a slice of the contents and the first error encountered.
|
|
func CollectErr[T any](seq iter.Seq2[T, error]) ([]T, error) {
|
|
var ret []T
|
|
for val, err := range seq {
|
|
if err != nil {
|
|
return ret, err
|
|
}
|
|
ret = append(ret, val)
|
|
}
|
|
|
|
return ret, nil
|
|
}
|