Golang:将切片转换为地图 [英] Golang: convert slices into map
问题描述
在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屋!