Golang: convert slices into map

前端 未结 4 1559
抹茶落季
抹茶落季 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 18:57

    If looking for a library you can use go-funk. This code may be less performant and not idiomatic in Go until we have Generics.

    var elements = []string{"abc", "def", "fgi", "adi"}
    
    elementsMap := funk.Map(
        funk.Chunk(elements, 2),
        func(x []string) (string, string) { // Slice to Map
            return x[0], x[1]
        },
    )
    
    fmt.Println(elementsMap) // map[abc:def fgi:adi]
    

    https://play.golang.org/p/-t-33z4aKM_j

提交回复
热议问题