Golang: convert slices into map

前端 未结 4 1512
抹茶落季
抹茶落季 2021-01-07 18:20

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 =

4条回答
  •  抹茶落季
    2021-01-07 19:14

    Try with range

    elements := []string{"abc", "def", "fgi", "adi"}
        elementMap := make(map[int]string)
        for i, data := range elements  {
                 elementMap[i] = data
            }
    
    fmt.Println(elementMap ) // map[0:abc 1:def 2:fgi 3:adi]
    

    https://play.golang.org/p/h6uZn5obLKg

提交回复
热议问题