如何在 Golang 中通过键获取地图值而不进行范围操作(htm/text 模板)?

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

How to get map value by key without range action (htm/text templates)? Golang

问题

我尝试只获取地图中的值,而不通过地图进行迭代。

例如,目前通过键获取地图值的方法如下:

{{range $key, $value := .mymap}}
    {{if $value = "myvalue"}}
        {{template "item" .}}
    {{end}}
{{end}}

也许有更好的方法只通过键获取地图值吗?例如:

{{print .mymap["key"]}}
英文:

I try just to get map value without iteration through the map.

For example, at the moment to get the map value by key this weird way:

{{range $key, $value := .mymap}}
    {{if $value = "myvalue"}}
        {{template "item" .}}
    {{end}}
{{end}}

May be there is any better way just to get map value by key? For example:

{{print .mymap["key"]}} 

答案1

得分: 16

使用索引从映射中获取值:

{{index .mymap "key"}}

playground示例

英文:

Use index to get a value from a map:

{{index .mymap "key"}}

playground example

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

发表评论

匿名网友

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

确定