-6

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

I'm thinking about ranging over all those key-values then create slice for that, but is there any simple code to do that?

0

2 Answers 2

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)
}
0
0

Go 1.18

It is now possible to write a generic function to extract all key-value pairs, i.e. the map entries, with any key and value types.

Notes:

  • the map iterations are still unordered — using generics doesn't change that.
  • the constraint for the map key must be comparable
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. If you really must return a slice of slices, then it can only be [][]any (or [][2]any) in order to hold different types.

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:

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.

Playground: https://go.dev/play/p/RwCGmp7MHKW

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.