Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

Creating a flat array from the map entries in Go

What is the shortest (and idiomatic) way to create an array from the keys and values of a map w/o compromising on time complexity too much?

For instance, from the following map:

map[string]string { "1":"a", "2":"b" }

I need to create the following array:

[]string{"1","a", "2","b"}

I can do this in Scala with following:

val myMap = Map("1" -> "a", "2" -> "b")
myMap.keySet ++ myMap.values

Thank you.

Upvotes: 5

Views: 25243

Answers (1)

eugenioy
eugenioy

Reputation: 12393

Simplest way would be to just iterate the map, since in Go the syntax would allow direct access to keys and values and dump them into the array.

m := map[string]string { "1":"a", "2":"b" }
arr := []string{}
for k, v := range m { 
   arr = append(arr, k, v)
}

One caveat here: In Go, map iteration order is randomized, as you can see here, under "Iteration Order":

https://blog.golang.org/go-maps-in-action

So if you want your resulting array to have a particular ordering, you should first dump the keys and order (as shown in that same blog entry).

Playground (without the sorting part):

https://play.golang.org/p/mCe6eEy25A

Upvotes: 22

Related Questions