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.
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, ","))
}
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, ","))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With