如何从地图获取键作为字符串数组?

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.

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, ","))
}

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, ","))
}

Interesting enough that I've got a bit strange result while tried to get keys list from the dictionary using @zola's approach. The snippet I was using:

package main

import "strings"

func main() {
    dict := map[string]int {"A": 1, "B": 2}
    keys := make([]string, len(dict))
    for key, _ := range dict {
        keys = append(keys, key)
    }
    println(strings.Join(keys, ", "))
    println(len(keys))
}

And, here is the output:

, , A, B

4

Seems like the capacity of the array storing keys was extended or something when it became full? Finally, I was using this approach:

package main

import "strings"

func main() {
    dict := map[string]int {"A": 1, "B": 2}
    keys := make([]string, len(dict))
    i := 0
    for key, _ := range dict {
        keys[i] = key  // explicit array element assignment instead of append function
        i += 1
    }
    println(strings.Join(keys, ", "))
    println(len(keys))
}

Not sure what is the reason. Probably it is a known bug, or I don't fully understand how Go works. For future reference, I'm using go version go1.10.3 darwin/amd64 and GoLand 2018.2.3.