Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a map value using a variable key in a Go template

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?

like image 855
Kyle Brandt Avatar asked Oct 01 '14 23:10

Kyle Brandt


People also ask

How do I get map values in go?

You can retrieve the value assigned to a key in a map using the syntax m[key] . If the key exists in the map, you'll get the assigned value. Otherwise, you'll get the zero value of the map's value type.

How does map work in Go?

In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.


1 Answers

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. 

https://golang.org/pkg/text/template#hdr-Functions

like image 120
OneOfOne Avatar answered Sep 21 '22 17:09

OneOfOne