[英]How to convert a map to a slice of entries?
I'm trying to convert key-value map to slice of pairs, for example given a map like:我正在尝试将键值映射转换为对切片,例如给定如下映射:
m := make(map[int64]int64)
m[521] = 4
m[528] = 8
How do I convert that into a slice of its entries, like: [[521, 4], [528, 8]]
如何将其转换为条目的一部分,例如:
[[521, 4], [528, 8]]
I'm thinking about ranging over all those key-values then create slice for that, but is there any simple code to do that?我正在考虑遍历所有这些键值然后为此创建切片,但是有没有简单的代码可以做到这一点?
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)
}
It is now possible to write a generic function to extract all key-value pairs, ie the map entries, with any key and value types.现在可以编写一个通用函数来提取所有键值对,即映射条目,具有任何键和值类型。
Notes:笔记:
type Pair[K, V any] struct {
First K
Second V
}
func Entries[M ~map[K]V, K comparable, V any](m M) []Pair[K, V] {
entries := make([]Pair[K, V], 0)
for k, v := range m {
entries = append(entries, Pair[K, V]{k, v})
}
return entries
}
The type Pair
here is used to preserve type safety in the return value.这里的类型
Pair
用于在返回值中保持类型安全。 If you really must return a slice of slices, then it can only be [][]any
(or [][2]any
) in order to hold different types.如果你真的必须返回一个切片,那么它只能是
[][]any
(或[][2]any
)以保存不同的类型。
If the map key and value have the same type, of course you can still use Pair
but you can also use a type-safe variation of the above:如果映射键和值具有相同的类型,当然您仍然可以使用
Pair
但您也可以使用上述类型安全的变体:
func Entries[T comparable](m map[T]T) [][2]T {
entries := make([][2]T, 0)
for k, v := range m {
entries = append(entries, [2]T{k, v})
}
return entries
}
Again, T
must be comparable
or stricter in order to work as a map key.同样,
T
必须具有comparable
或更严格才能用作映射键。
Playground: https://go.dev/play/p/RwCGmp7MHKW游乐场: https ://go.dev/play/p/RwCGmp7MHKW
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.