github.com/haraldrudell/parl@v0.4.176/iters/if-iterator.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package iters 7 8 // Iterator allows traversal of values. 9 // - iterate over an unimported type using an iterator returning 10 // a derived value such as an interface type 11 // - convert a slice value-by-value, ie. return interface-type values from 12 // a struct slice 13 // - iterate over pointers to slice values 14 // - iterate over function 15 // - obtain errors occurring in the iterator or release iterator resources 16 // 17 // The iterator interface is optimized for use in the Go “for” clause. 18 // Iterators in the iters package are thread-safe but 19 // thread-safety depends on iterator implementation. 20 // 21 // Usage in Go “for” clause: 22 // 23 // for i, iterator := NewIterator().Init(); iterator.Cond(&i); { 24 // println(i) 25 // 26 // var err error 27 // for i, iterator := NewIterator().Init(); iterator.Cond(&i, &err); { 28 // println(i) 29 // } 30 // if err != nil { 31 // 32 // var err error 33 // var iterator = NewIterator() 34 // for i := 0; iterator.Cond(&i); { 35 // println(i) 36 // } 37 // if err = iterator.Cancel(); err != nil { 38 type Iterator[T any] interface { 39 // Init implements the right-hand side of a short variable declaration in 40 // the init statement of a Go “for” clause 41 // 42 // for i, iterator := iters.NewSlicePointerIterator(someSlice).Init(); iterator.Cond(&i); { 43 // // i is pointer to slice element 44 Init() (iterationVariable T, iterator Iterator[T]) 45 // Cond implements the condition statement of a Go “for” clause 46 // - condition is true if iterationVariable was assigned a value and the iteration should continue 47 // - the iterationVariable is updated by being provided as a pointer. 48 // iterationVariable cannot be nil 49 // - errp is an optional error pointer receiving any errors during iterator execution 50 // 51 // Usage: 52 // 53 // for i, iterator := iters.NewSlicePointerIterator(someSlice).Init(); iterator.Cond(&i); { 54 // // i is pointer to slice element 55 Cond(iterationVariablep *T, errp ...*error) (condition bool) 56 // Next advances to next item and returns it 57 // - if hasValue true, value contains the next value 58 // - otherwise, no more items exist and value is the data type zero-value 59 Next() (value T, hasValue bool) 60 // Cancel stops an iteration 61 // - after Cancel invocation, Cond, Next and Same indicate no value available 62 // - Cancel returns the first error that occurred during iteration, if any 63 // - an iterator implementation may require Cancel invocation 64 // to release resources 65 // - Cancel is deferrable 66 Cancel(errp ...*error) (err error) 67 }