我在GO中有一张地图:
var userinputmap = make(map[string]string)
其中的值如下:
userinputmap["key1"] = value1
userinputmap["key2"] = value2
userinputmap["key3"] = value3
现在,如何以逗号分隔格式生成包含上述键的字符串?
output:= "key1,key2,key3"
非常感谢。
答案 0 :(得分:4)
在循环中迭代并将键附加到字符串:
package main
import "fmt"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
output :=""
for key,_ := range userinputmap {
output +=(key+",")
}
output = output[:len(output)-1]
fmt.Println(output)
}
答案 1 :(得分:1)
另一种选择是将所有密钥收集到切片中,然后使用strings.Join
方法加入它们。
package main
import "fmt"
import "strings"
func main() {
var userinputmap = make(map[string]string)
userinputmap["key1"] = "value1"
userinputmap["key2"] = "value2"
userinputmap["key3"] = "value3"
keys := []string {}
for k, _ := range userinputmap {
keys = append(keys, k)
}
keys_string := strings.Join(keys, ",")
fmt.Println(keys_string)
}