Skip to content

Instantly share code, notes, and snippets.

@samix73
Created September 16, 2024 12:19
Show Gist options
  • Save samix73/23c01223beb587571143d951eab74053 to your computer and use it in GitHub Desktop.
Save samix73/23c01223beb587571143d951eab74053 to your computer and use it in GitHub Desktop.
This Go code demonstrates how to convert a slice into a map using generics. It includes a generic function `SliceToMap` that takes a slice, and a key function to generate keys for the resulting map. The code provides a simple example of converting a string slice to a map with integer keys.
package main
import "fmt"
func SliceToMap[I ~[]V, K comparable, V any](arr I, keyFunc func(i int) K) map[K]V {
m := make(map[K]V)
for i := range arr {
m[keyFunc(i)] = arr[i]
}
return m
}
func main() {
s := []string{
"Hello", "Bye", "Bye",
}
m := SliceToMap(s, func(i int) int {
return i
})
fmt.Println(m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment