繁体   English   中英

使用 Go 模板中的变量键访问 map 值

[英]Access a map value using a variable key in a Go template

如何在不迭代的情况下使用变量键查找 map 的值?

因此,可以使用$x.key1在变量 map $x 上查找常量键,但是可以执行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

一种更简单的方法是: {{.Amap.key1}} 但是,这仅在密钥是字母数字时才有效。 如果没有,您需要使用index访问它。

文档

- 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM