Golang:将切片转换为地图 [英] Golang: convert slices into map

查看:97
本文介绍了Golang:将切片转换为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中是否存在一种将切片转换为地图的简便方法?就像在perl中将数组转换为哈希一样,通过%hash = @array这样的简单分配就可以轻松完成 上面的代码会将数组中的所有元素转换为哈希,其中键是偶数索引元素,而值将是数组的奇数索引元素.

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.

在我的Go代码中,我有一些字符串切片,并希望将其转换为地图.我想知道是否有Go的库代码可以做到这一点.

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"}
}

元素切片应转换为字符串映射elementMap.

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

谢谢

推荐答案

使用for循环:

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]
}

在操场上可运行的示例

标准库没有执行此操作的功能.

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

这篇关于Golang:将切片转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆