Back to Lo

Core Keybyerr

docs/data/core-keybyerr.md

1.53.0706 B
Original Source

Transforms a slice to a map using a pivot callback to compute keys. Stops iteration immediately when an error is encountered.

go
// Error case - stops on first error
result, err := lo.KeyByErr([]string{"a", "aa", "aaa", ""}, func(str string) (int, error) {
    if str == "" {
        return 0, fmt.Errorf("empty string not allowed")
    }
    return len(str), nil
})
// map[int]string(nil), error("empty string not allowed")
go
// Success case
result, err := lo.KeyByErr([]string{"a", "aa", "aaa"}, func(str string) (int, error) {
    if str == "" {
        return 0, fmt.Errorf("empty string not allowed")
    }
    return len(str), nil
})
// map[int]string{1: "a", 2: "aa", 3: "aaa"}, nil