英文:
How to get the keys as string array from reflect MapKeys?
问题
我需要使用strings.Join(invoicesBatch, ",")
来连接一个字符串数组。
但是,我从使用reflect.ValueOf(invoiceList).MapKeys()
获取的数组是reflect.Value
数组。有没有一种简单的方法将它们转换为字符串数组。
该映射是使用字符串键进行初始化的。
英文:
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.
答案1
得分: 41
你可以使用for循环和range来获取键的切片,而不是使用反射。代码如下:
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, ","))
}
这段代码会输出键的切片。
英文:
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, ","))
}
答案2
得分: 18
你需要使用循环,但不需要每次都创建一个新的切片,因为我们已经知道长度。示例:
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, ","))
}
英文:
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, ","))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论