lo
lo copied to clipboard
New func to add error to response
When we convert an array of strings to numbers, the Map function is called.
numbers := Map(strs, func(item string, index int) int {
number, err := strconv.Atoi(item)
if err != nil {
// log
return 0
}
return number
})
Errors during conversion must be ignored and the loop cannot be terminated early. I want to increase the definition of the function with error:
func Map[T any, R any](collection []T, iteratee func(item T, index int) (R, error)) ([]R, error) {
result := make([]R, len(collection))
var err error
for i, item := range collection {
result[i],err = iteratee(item, i)
if err != nil {
// log
return nil, err
}
}
return result, nil
}