github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/pkg/goutils/iterate/README.md (about) 1 Iterate - ForEach, FindFirst and FindFirstError generic iterators 2 ================================================================= 3 4 Iterate package provides routines to iterate slice-like and map-like structures. 5 6 The main idea is the following. You have some interface or structure that has a simple method that iterates over all available values. Using the generic routines provided by this package, you can quickly implement data find and error find. 7 8 ## Examples: 9 10 ```go 11 type ( 12 ITested interface { 13 Fields(enum func(name string)) 14 } 15 testedStruct struct { 16 fields []string 17 } 18 ) 19 20 func (s *testedStruct) Fields(enum func(name string)) { 21 for _, name := range s.fields { 22 enum(name) 23 } 24 } 25 ``` 26 27 ### Find: 28 ```go 29 var tested ITested = &testedStruct{fields: []string{"a", "b", "c"}} 30 ok, data := FindFirstData(tested.Fields, "b") 31 // ok = true 32 // data = "b" 33 34 // … 35 36 ok, data := FindFirst(tested.Fields, func(data string) bool { return data > "a" }) 37 // ok = true 38 // data = "b" 39 ``` 40 41 ### Find first error: 42 ```go 43 var tested ITested = &testedStruct{fields: []string{"a", "b", "c"}} 44 45 data, err := FindFirstError(tested.Fields, func(data string) error { 46 if data == "b" { 47 return fmt.Errorf("error at «%v»", data) 48 } 49 return nil 50 }) 51 // err = `error at «b»` 52 // data = "b" 53 ```