Opinionated answer: If a container type cannot iterate over its elements 
without fail, I would refrain from trying to build a standard iterator for 
this container type. You'd be shoehorning an iterator that can fail into 
the iter API that is not designed for dealing with errors. 

Putting half-witted opinions aside, this thread in /r/golang 
<https://www.reddit.com/r/golang/comments/1eyc4ov/go_123_iterators_how_to_return_errors/>
 might 
provide some food for thought. If you want to go with one of your three 
options, I'd favor the first one for its simplicity. It seems to work 
<https://go.dev/play/p/AHW2J5bl6FO>, and I don't see how the other two 
improve over the first one. 

On Thursday, August 29, 2024 at 2:41:47 PM UTC+2 Dmitriy P wrote:

> What is the best way to handle errors with iterators?
>
> How to handle error when we have some object and some type paginates data 
> (e.g. database/sql.Rows or 
> https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#ListObjectsV2Paginator
> )?
> I found three, but which should be preferable or maybe I've missed some?
>
> ```go
> type Object smth.Smth
> type Paginator interface {
> GetNext(ctx) ([]Object, error) // func doing heavy request over internet 
> HaveNext() bool 
> }
> ```
>
> ```go
> func Iter(ctx, data) iter.Seq2[Object, error]
>
> for obj, err := Iter(...) {
> if err != nil {
> return err
> }
> // do smth with Object
> }
> ```
>
> ```go
> func IterWithErr(ctx, data, err *error) iter.Seq[Object]
>
> var err error
> for obj := IterWithErr(..., &err) {
> // do smth with Object
> }
> if err != nil {
> return err
> }
> ```
>
> ```go
> func IterOverIter(ctx, data) iter.Seq2[iter.Seq[Object], error]
>
> for page, err := IterOverIter(...) {
> if err != nil {
> return err
> }
> for obj := page(...) {
> // do smth with Object
> }
> }
> ```
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/bf855750-c4d7-4e22-8a79-fb2a4369ed6bn%40googlegroups.com.

Reply via email to