-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Description
Proposal Details
Idiomatic go functions are often in the form func (...) (T, err).
When creating iterators, it is equally common for the underlying functions to potentially return an error as each element in the iteration is created. For example, records might be read from a database, or requests from a client, etc.
Therefore, it will be relatively common for iterators of the form iter.Seq2[T, error] to be defined, as each element may produce an error. Sometimes a non-nil error will indicate a problem with that element only, but in many situations it will correspond to a termination of the iterator.
slices.Collect() is a helpful function to generate []T from iter.Seq[T]. It would be helpful to have an analogue to handle iter.Seq2[T, error]
My proposal is to add something similar to the following to the slices package:
func CollectError[T any](seq iter.Seq2[T, error]) ([]T, error) {
var err error
result := slices.Collect[T](func(yield func(t T) bool) {
for k, v := range seq {
if v != nil {
err = v
return
}
if !yield(k) {
return
}
}
})
return result, err
}If an iteration includes a non-nil error, a slice of []T will be returned including all elements up to (but not including) the erroring iteration, along with the error.
Should no error be found, it will return ([]T, nil).
While this is not a large or complex function, iterator syntax is a little unwieldy and this would allow gophers to more easily consume iter.Seq2[T, err] iterators without being exposed to yield.
As mentioned earlier, some iter.Seq2[T, err] iterators will return a non-nil error and then continue. They would not be suitable to use with CollectError - but it would not be encouraged to collect these elements into a slice anyway; they should be processed as they arrive instead.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status