将GO MAP中的关键数据追加。

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

Append key data from the GO MAP

问题

你可以使用循环遍历地将所有的键连接成一个以逗号分隔的字符串。以下是一个示例代码:

package main

import (
	"fmt"
	"strings"
)

func main() {
	userinputmap := make(map[string]string)
	userinputmap["key1"] = "value1"
	userinputmap["key2"] = "value2"
	userinputmap["key3"] = "value3"

	keys := make([]string, 0, len(userinputmap))
	for key := range userinputmap {
		keys = append(keys, key)
	}

	output := strings.Join(keys, ",")
	fmt.Println(output)
}

这段代码会输出:key1,key2,key3

英文:

I have a map in GO of the type :

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"

答案1

得分: 7

在循环中迭代并将键添加到字符串中:

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

在循环中迭代并将键添加到字符串中。

英文:

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

答案2

得分: 2

另一种选择是将所有的键收集到一个切片中,然后使用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)
}

请注意,这是一个Go语言的示例代码,用于将一个map中的键连接成一个字符串并打印出来。

英文:

Another option is to collect all your keys into a slice and then use strings.Join method to join them.

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

huangapple
  • 本文由 发表于 2015年9月30日 07:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32855393.html
匿名

发表评论

匿名网友

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

确定