Reputation: 550
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.
Upvotes: 22
Views: 56785
Reputation: 6397
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, ","))
}
Upvotes: 42
Reputation: 33637
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, ","))
}
Upvotes: 18