Back to Lo

Core Meanbyerr

docs/data/core-meanbyerr.md

1.53.0653 B
Original Source

Calculates the mean of values computed by a predicate. Returns 0 for an empty collection.

If the iteratee returns an error, iteration stops and the error is returned.

go
list := []string{"aa", "bbb", "cccc", "ddddd"}
result, err := lo.MeanByErr(list, func(item string) (float64, error) {
    return float64(len(item)), nil
})
// 3.5, <nil>

Example with error:

go
list := []string{"aa", "bbb", "cccc", "ddddd"}
result, err := lo.MeanByErr(list, func(item string) (float64, error) {
    if item == "cccc" {
        return 0, fmt.Errorf("cccc is not allowed")
    }
    return float64(len(item)), nil
})
// 0, error("cccc is not allowed")