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

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

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{
		&quot;A&quot;: 1, &quot;B&quot;: 2,
	}
	keys := reflect.ValueOf(a).MapKeys()
	strkeys := make([]string, len(keys))
	for i := 0; i &lt; len(keys); i++ {
		strkeys[i] = keys[i].String()
	}
	fmt.Print(strings.Join(strkeys, &quot;,&quot;))
}

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:

确定