英文:
Access a map value using a variable key in a Go template
问题
如何在不迭代的情况下,通过使用变量键查找地图的值?
因此,可以使用$x.key1
在变量地图$x
上查找常量键,但是否可以使用amap.$key
这样做呢?
英文:
How can I look up the value of a map by using a variable key without iterating?
So one can lookup a constant key on variable map $x with $x.key1
, but is it possible to do amap.$key
?
答案1
得分: 193
你使用了index
函数:
{{index .Amap "key1"}}
index
通过以下参数对其第一个参数进行索引,并返回结果。因此,在Go语法中,"index x 1 2 3"表示x[1][2][3]。每个索引项必须是map、slice或array类型。
https://golang.org/pkg/text/template#hdr-Functions
英文:
You use the index
function:
{{index .Amap "key1"}}
index
Returns the result of indexing its first argument by the
following arguments. Thus "index x 1 2 3" is, in Go syntax,
x[1][2][3]. Each indexed item must be a map, slice, or array.
答案2
得分: 14
一个更简单的方法是使用{{.Amap.key1}}
。然而,这只适用于键是字母数字的情况。如果不是,你需要使用index
来访问它。
根据文档:
- 数据的键名,必须是一个映射,以句点开头,例如
.Key
结果是由键索引的映射元素值。
键调用可以链接并与任何深度的字段组合:
.Field1.Key1.Field2.Key2
尽管键必须是字母数字标识符,但与字段名不同,它们不需要以大写字母开头。
键也可以在变量上进行评估,包括链接:
$x.key1.key2
英文:
A simpler way would be to do: {{.Amap.key1}}
. However, this will only work if the key is alphanumeric. If not, you'll need to access it using index
.
From the documentation:
- The name of a key of the data, which must be a map, preceded
by a period, such as
.Key
The result is the map element value indexed by the key.
Key invocations may be chained and combined with fields to any
depth:
.Field1.Key1.Field2.Key2
Although the key must be an alphanumeric identifier, unlike with
field names they do not need to start with an upper case letter.
Keys can also be evaluated on variables, including chaining:
$x.key1.key2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论