简体   繁体   English

附加来自 GO MAP 的关键数据

[英]Append key data from the GO MAP

I have a map in GO of the type :我有一个 GO 类型的地图:

var userinputmap = make(map[string]string)

The values in it are like :其中的值如下:

userinputmap["key1"] = value1
userinputmap["key2"] = value2
userinputmap["key3"] = value3

How can I generate a string that contains al the above keys in comma seprated format?如何以逗号分隔格式生成包含上述所有键的字符串?

output:= "key1,key2,key3"

iterate in a loop and append key to string:在循环中迭代并将键附加到字符串:

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)
}

Another option is to collect all your keys into a slice and then use strings.Join method to join them.另一种选择是将所有键收集到一个切片中,然后使用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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM