如何从反射中的MapKeys获取键的字符串数组?

huangapple go评论103阅读模式
英文:

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来获取键的切片,而不是使用反射。代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. data := map[string]int{
  8. "A": 1,
  9. "B": 2,
  10. }
  11. keys := make([]string, 0, len(data))
  12. for key := range data {
  13. keys = append(keys, key)
  14. }
  15. fmt.Print(strings.Join(keys, ","))
  16. }

这段代码会输出键的切片。

英文:

instead of using reflection you can use a for loop and range to get a slice of keys like this

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. data := map[string]int{
  8. "A": 1,
  9. "B": 2,
  10. }
  11. keys := make([]string, 0, len(data))
  12. for key := range data {
  13. keys = append(keys, key)
  14. }
  15. fmt.Print(strings.Join(keys, ","))
  16. }

答案2

得分: 18

你需要使用循环,但不需要每次都创建一个新的切片,因为我们已经知道长度。示例:

  1. func main() {
  2. a := map[string]int{
  3. "A": 1, "B": 2,
  4. }
  5. keys := reflect.ValueOf(a).MapKeys()
  6. strkeys := make([]string, len(keys))
  7. for i := 0; i < len(keys); i++ {
  8. strkeys[i] = keys[i].String()
  9. }
  10. fmt.Print(strings.Join(strkeys, ","))
  11. }
英文:

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:

  1. func main() {
  2. a := map[string]int{
  3. &quot;A&quot;: 1, &quot;B&quot;: 2,
  4. }
  5. keys := reflect.ValueOf(a).MapKeys()
  6. strkeys := make([]string, len(keys))
  7. for i := 0; i &lt; len(keys); i++ {
  8. strkeys[i] = keys[i].String()
  9. }
  10. fmt.Print(strings.Join(strkeys, &quot;,&quot;))
  11. }

huangapple
  • 本文由 发表于 2017年1月17日 14:13:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41690156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定