如何解码 Golang 中的 map?

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

How to Decode map golang

问题

你运行代码后得到了以下地图:
map[from:0 key:<nil> price:Desc title:stack]
你想要获取frompricetitle的值。
请帮助我。

英文:

I run my code and I get map like that:
map[from:0 key:<nil> price:Desc title:stack]
I want to get value from,price,title

please help me

答案1

得分: 1

一旦你构建好了地图,你可以通过提供键来访问地图的值。语法如下:

value := myMap[myKey]

键的类型可以是任何可以通过比较运算符(>===<=等)进行评估的类型。根据你的示例,看起来你正在使用字符串作为键。

以下是一个示例:

m := map[string]interface{}{
    "from": 0,
    "key": nil,
    "price": "Desc",
    "title": "task",
}

// 获取 price 的值
price := m["price"]
fmt.Println(price)

// 获取 title
title := m["title"]
fmt.Println(title)

// 遍历地图的所有键值对
for key, value := range m {
    fmt.Println(key, ":", value)
}

在 Go Playground 中查看示例

英文:

Once you have your map constructed, you can access a value of the map by providing the key. The syntax is:

value := myMap[myKey]

The key's type can be any type that can be evaluated by a comparison operator ( &gt;=, ==, &lt;=, etc...). For your example it looks like you are using strings for keys.

Here's an example:

m := map[string]interface{}{
	&quot;from&quot;: 0,
	&quot;key&quot;: nil,
	&quot;price&quot;: &quot;Desc&quot;,
	&quot;title&quot;: &quot;task&quot;,
}
	
// Get the value of price
price := m[&quot;price&quot;]
fmt.Println(price)

// Get the title
title := m[&quot;title&quot;]
fmt.Println(title)
	
// Loop through all of the map&#39;s key-value pairs
for key, value := range m {
	fmt.Println(key, &quot;:&quot;, value)
}

Example in Go Playground

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

发表评论

匿名网友

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

确定