Golang: convert slices into map

Nikhil Mulley picture Nikhil Mulley · Jul 26, 2016 · Viewed 32.5k times · Source

Is there an easy/simple means of converting a slice into a map in Golang? Like converting an array into hash in perl is easy to do with simple assignment like %hash = @array this above will convert all the elements in the array into a hash, with keys being even-numbered index elements while the values will be odd-numbered index elements of the array.

In my Go code, I have slices of string and would like to convert it into a map. I am wondering if there is a Go's library code to do this.

func main() {
  var elements []string
  var elementMap map[string]string
  elements = []string{"abc", "def", "fgi", "adi"}
}

elements slice should be converted into map of strings, elementMap.

thanks

Answer

Cerise Limón picture Cerise Limón · Jul 26, 2016

Use a for loop:

elements = []string{"abc", "def", "fgi", "adi"}
elementMap := make(map[string]string)
for i := 0; i < len(elements); i +=2 {
    elementMap[elements[i]] = elements[i+1]
}

runnable example on the playground

The standard library does not have a function to do this.