mirror of
https://github.com/samber/lo.git
synced 2026-04-22 23:47:11 +08:00
2.0 KiB
2.0 KiB
name, slug, sourceRef, category, subCategory, playUrl, variantHelpers, similarHelpers, position, signatures
| name | slug | sourceRef | category | subCategory | playUrl | variantHelpers | similarHelpers | position | signatures | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Associate | associate | slice.go#L389 | core | slice | https://go.dev/play/p/WHa2CfMO3Lr |
|
|
240 |
|
Builds a map from a slice using a transform function that yields key/value pairs for each item. Perfect for converting collections to lookup maps.
Associate
Transforms each element into a key-value pair. Later items with the same key will overwrite earlier ones.
type foo struct {
baz string
bar int
}
in := []*foo{{baz: "apple", bar: 1}, {baz: "banana", bar: 2}}
m := lo.Associate(in, func(f *foo) (string, int) {
return f.baz, f.bar
})
// m: map[string]int{"apple": 1, "banana": 2}
AssociateI
Variant that includes the element index in the transform function, useful when you need the position in the original slice.
type User struct {
Name string
Age int
}
users := []User{
{Name: "Alice", Age: 25},
{Name: "Bob", Age: 30},
}
result := lo.AssociateI(users, func(user User, index int) (string, int) {
return fmt.Sprintf("%s-%d", user.Name, index), user.Age
})
// result: map[string]int{"Alice-0": 25, "Bob-1": 30}
SliceToMap
Alias for Associate - provides the same functionality with a more explicit name.
products := []string{"apple", "banana", "cherry"}
result := lo.SliceToMap(products, func(product string) (string, int) {
return product, len(product)
})
// result: map[string]int{"apple": 5, "banana": 6, "cherry": 6}