Go template to print an array's length

huangapple go评论120阅读模式
英文:

Go template to print an array's length

问题

我没有Go的经验。我使用一个叫做Podman的工具,它是用Go语言编写的。它在文档中描述了--format选项,如下所示:

-f, --format string   将输出格式化为Go模板或json(默认为“json”)

我可以通过以下方式获取我想要的结果:

podman inspect localhost/myimage --format "{{.RootFS.Layers.length}}"

但是,如果我想要获取元素的数量,我该怎么做?我尝试了不同的字段,如.count.length.len,但总是得到以下错误信息:

无法在类型[]digest.Digest中评估字段FieldName

我还尝试了{{len(RootFS.Layers)}}这样调用。我只是一种蛮力的方式。当我执行上述操作时,我得到以下错误信息:

> ERRO[0000] Error printing inspect output: template: all inspect:1: unexpected "()" in operand

请问,获取数组元素数量的正确Go模板是什么?

英文:

I have no Go experience. I use a tool, Podman, which is written in Go, it documents its --format option as,

-f, --format string   Format the output to a Go template or json (default "json")

I can see what I want with,

podman inspect localhost/myimage --format "{{.RootFS.Layers.length}}"

But, if I want to get the count of how many elements there are what do I do? I've tried different fields with .count and .length and .len, but I always get,

can't evaluate field FieldName in type []digest.Digest

I've also tried invoking this as {{len(RootFS.Layers)}}. I'm just kind of brute forcing it. When I do the above, I get,

> ERRO[0000] Error printing inspect output: template: all inspect:1: unexpected "(" in operand

What is the right Go Template to get an array's element count?

答案1

得分: 2

go templating语言和语法与go语言本身不同 - 所以你看到的len(RootFS.Layers)是不起作用的。

根据模板文档,你正在使用正确的函数len,但模板语法不需要括号。所以使用:

{{ len .RootFS.Layers }}

FYI:一个关于Go模板的快速介绍

英文:

The go templating language and syntax is different from the go language itself - so len(RootFS.Layers) as you have seen does not work.

From the template docs, you are using the correct function len but the template syntax does not require parenthesis. So use:

{{ len .RootFS.Layers }}

FYI: a quick intro to Go templates.

huangapple
  • 本文由 发表于 2021年10月5日 10:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/69444172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定