【问题标题】:How to index a slice element?如何索引切片元素?
【发布时间】:2012-09-23 23:10:13
【问题描述】:

我有一片:Keys []* datastore.Key

如何在模板文件中索引其中之一?我猜到了{{.Keys[3] }},但这不起作用,我搜索了很多但没有任何线索。

欢迎任何建议,谢谢。

【问题讨论】:

    标签: slice go-templates


    【解决方案1】:

    像这样使用index 命令:

    {{index .Keys 3}}
    

    【讨论】:

    • @DeanSinaean:来自html/template 文档的概述:“有关如何对模板本身进行编程的信息,请参阅文本/模板的文档。”
    • @nemo 你知道如何避免索引超出范围的问题吗?
    • @sh0umik 你是什么意思?访问不在所述数组中的元素时,您会遇到索引超出范围错误。没有什么特别的技巧可以避免这种情况,只是不要这样做。如果你想要一个“安全”的索引方法,你总是可以编写自己的函数来访问将自行处理越界错误的数据。
    【解决方案2】:

    如 html/template 包中所述,大多数示例实际上位于 text/template pkg 文档中。见http://golang.org/pkg/text/template/

    来自文档

    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.
    

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2013-08-03
      • 2021-12-31
      • 2018-07-29
      • 2021-07-28
      相关资源
      最近更新 更多