Skip to content

Instantly share code, notes, and snippets.

@kfelter
Created August 18, 2023 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfelter/303a9c3d6001990249bad971064e15af to your computer and use it in GitHub Desktop.
Save kfelter/303a9c3d6001990249bad971064e15af to your computer and use it in GitHub Desktop.
Golang Convert a slice of structs to a map of structs: Mastering Go Application Design
package main
import "fmt"
// sliceToMap creates a new map of type map[string]T and uses func 'f' to set the key of the new map
// from the slice
func sliceToMap[T any](items []T, f func(item T) string) map[string]T {
itemMap := make(map[string]T, len(items))
for _, item := range items {
itemMap[f(item)] = item
}
return itemMap
}
// Example
type Item struct {
ID string
Name string
Price int
}
type Element struct {
Name string
Weight int
}
func main() {
// Create a slice of items
items := []Item{
{"item1", "Item 1 Name", 100}, {"item2", "Item 2 Name", 200}, {"item3", "Item 3 Name", 300},
}
// Convert the slice to a map using the ID field as the key
itemMap := sliceToMap(items, func(item Item) string {
return item.ID
})
fmt.Println("itemMap:", itemMap)
// map[item1:{item1 Item 1 Name 100} item2:{item2 Item 2 Name 200} item3:{item3 Item 3 Name 300}]
elements := []Element{
{"element1", 100}, {"element2", 200}, {"element3", 300},
}
elementMap := sliceToMap(elements, func(element Element) string {
return element.Name
})
fmt.Println("elementMap:", elementMap)
// map[element1:{element1 100} element2:{element2 200} element3:{element3 300}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment