How to get the keys as string array from map?
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, ","))
}