英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论