Created
September 16, 2024 12:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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