Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the keys as string array from map?

Tags:

go

I need to use strings.Join(invoicesBatch, ",") to join a string array. But the array I got from the map using reflect.ValueOf(invoiceList).MapKeys() is reflect.Value array. Is there a easy way to convert them into a string array.

The map was initialized with string key.

like image 856
user4142018 Avatar asked Jan 17 '17 06:01

user4142018


2 Answers

instead of using reflection you can use a for loop and range to get a slice of keys like this

package main

import (
"fmt"
"strings"
)

func main() {
  data := map[string]int{
      "A": 1,
      "B": 2,
  }
  keys := make([]string, 0, len(data))
  for key := range data {
    keys = append(keys, key)
  }

  fmt.Print(strings.Join(keys, ","))
}
like image 108
zola Avatar answered Sep 19 '22 16:09

zola


You will need to use loop but you won't need to create a new slice every time as we already know the length. Example:

func main() {
    a := map[string]int{
        "A": 1, "B": 2,
    }
    keys := reflect.ValueOf(a).MapKeys()
    strkeys := make([]string, len(keys))
    for i := 0; i < len(keys); i++ {
        strkeys[i] = keys[i].String()
    }
    fmt.Print(strings.Join(strkeys, ","))
}
like image 21
Ankur Avatar answered Sep 21 '22 16:09

Ankur