Golang: convert slices into map

怎甘沉沦 提交于 2019-12-01 03:05:49

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.

There is currently no way to do it the perl way. You just have to iterate the slice, and place the slice elements in your map, e.g. as the map's key:

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

    // initialize map
    elementMap = make(map[string]string)

    // put slice values into map
    for _, s := range elements {  
        elementMap[s] = s
        // or just keys, without values: elementMap[s] = ""
    }

    // print map
    for k := range elementMap {
        fmt.Println(k)
    }
}

Depending on what you want to do, you have to keep one thing in mind: map keys are unique, so if your slice contains duplicate strings you might want to keep count by using a map[string]int:

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

    // initialize map
    elementMap = make(map[string]int)

    // increment map's value for every key from slice
    for _, s := range elements {  
        elementMap[s]++
    }

    // print map
    for k, v := range elementMap {
        fmt.Println(k, v)
    }
}

And you can always wrap that functionality in a func:

func sliceToStrMap(elements []string) map[string]string {
    elementMap := make(map[string]string)
    for _, s := range elements {
        elementMap[s] = s
    }
    return elementMap
}

func sliceToIntMap(elements []string) map[string]int {
    elementMap := make(map[string]int)
    for _, s := range elements {
        elementMap[s]++
    }
    return elementMap
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!