在 Go 模板中使用可变键访问映射值 [英] Access a map value using a variable key in a Go template
本文介绍了在 Go 模板中使用可变键访问映射值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不迭代的情况下使用可变键查找地图的值?
How can I look up the value of a map by using a variable key without iterating?
所以我们可以用$x.key1
在变量映射$x上查找一个常量键,但是是否可以做amap.$key
?
So one can lookup a constant key on variable map $x with $x.key1
, but is it possible to do amap.$key
?
推荐答案
你使用了index
函数:
{{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.
https://golang.org/pkg/text/template#hdr-Functions
这篇关于在 Go 模板中使用可变键访问映射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文