lo icon indicating copy to clipboard operation
lo copied to clipboard

New func to add error to response

Open woniu317 opened this issue 2 years ago • 0 comments

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
}

woniu317 avatar Dec 19 '23 06:12 woniu317