从map[string]interface{}创建字符串。

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

Create string from map[string]interface{}

问题

你可以使用字符串拼接的方式来形成你想要的字符串。在Go语言中,你可以使用加号运算符(+)来连接字符串。下面是一个示例代码:

data := map[string]interface{}{
    "username": 'username1',
    "password": 'password1',
}

str := "username='" + data["username"].(string) + "', password='" + data["password"].(string) + "'"

在上面的代码中,我们首先定义了一个data的map,然后使用加号运算符将map中的键值对连接成一个字符串。注意,我们使用了类型断言(data["username"].(string))来将接口类型转换为字符串类型。

希望这可以帮助到你!如果你还有其他问题,请随时问我。

英文:
    data := map[string]interface{}{
	        "username":       'username1',
	        "password":       'password1'
        }

I have a map[string]interface{} data, I want to form a string like below

str = "username='username1', password='password1'"

How can I form string like above i.e. key1='value1', key2='value2'....
I am new to golang
I tried append() but was facing issues like cannot append []string to variable type string

答案1

得分: 1

你尝试过什么了吗?有很多方法可以实现你想要做的事情。有些方法更高效,有些方法更容易编写...以下是一种快速实现你所需功能的方法:

func PrintStr(m map[string]interface{}) {
    parts := make([]string, 0, len(m))
    for k, v := range m {
        parts = append(parts, fmt.Sprintf("%s=%v", k, v))
    }
    fmt.Printf("%s\n", strings.Join(parts, ";"))
}
英文:

Have you tried anything? There's lots of ways to do what you're trying to do. Some more peprformant than others, some easier to write... This would be a quick way to implement what you need:

func PrintStr(m map[string]interface{}) {
    parts := make([]string, 0, len(m))
    for k, v := range m {
        parts = append(parts, fmt.Sprintf("%s=%v", k, v))
    }
    fmt.Printf("%s\n", strings.Join(parts, ";"))
}

答案2

得分: 0

遍历数据范围。如果不是第一个,则添加逗号。写入键。写入等号。写入值。

data := map[string]interface{}{
	"username": "username1",
	"password": "password1",
}
var sb strings.Builder
for k, v := range data {
	if sb.Len() > 0 {
		sb.WriteString(", ")
	}
	sb.WriteString(k)
	sb.WriteString(`="`)
	sb.WriteString(fmt.Sprint(v))
	sb.WriteString(`"`)
}
s := sb.String()
fmt.Println(s)
英文:

Range over data. Add comma if not first. Write key. Write =. Write value.

data := map[string]interface{}{
	"username": "username1",
	"password": "password1",
}
var sb strings.Builder
for k, v := range data {
	if sb.Len() > 0 {
		sb.WriteString(", ")
	}
	sb.WriteString(k)
	sb.WriteString(`="`)
	sb.WriteString(fmt.Sprint(v))
	sb.WriteString(`"`)
}
s := sb.String()
fmt.Println(s)

huangapple
  • 本文由 发表于 2022年10月3日 01:19:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/73927845.html
匿名

发表评论

匿名网友

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

确定