我正在尝试将键值映射转换为2个值的切片,例如:
slices := make(map[int64]int64)
slices[int64(521)] = int64(4)
slices[int64(528)] = int64(8)
// how do i convert that to become
// [[521, 4], [528, 8]]
我正在考虑所有这些键值,然后为此创建切片,但是有没有简单的代码可以做到这一点?
答案 0 :(得分:1)
package main
import "fmt"
func main() {
//create a map
m := map[int64]int64{512: 8, 513: 9, 234: 9, 392: 0}
//create a slice to hold required values
s := make([][]int64, 0)
//range over map `m` to append to slice `s`
for k, v := range m {
// append each element, with a new slice []int64{k, v}
s = append(s, []int64{k, v})
}
fmt.Println(s)
}