How to Convert a Slice to a Map in Go

Convert a Go slice to a map by iterating through the slice and assigning key-value pairs to a new map instance.

Convert a slice of key-value pairs to a map by iterating through the slice and assigning each pair to the map. Use a for loop with range to access elements and set them in the map.

slice := []struct{ K, V string }{{"a", "1"}, {"b", "2"}}
result := make(map[string]string)
for _, item := range slice {
    result[item.K] = item.V
}