英文:
Struct Variable Names in Go Templates
问题
我正在尝试使用内置的http/template库将一个结构体传递给Go模板。然而,我发现如果我将结构体的变量命名为首字母小写,它们在模板中不会被渲染,但如果我将它们命名为首字母大写,它们就会被渲染。我在这里看到结构体的首字母可以是大写或小写。那么,为什么Go模板引擎不会同时渲染两者呢?
请参考以下示例:
提前感谢。
英文:
I'm trying to pass a struct into a Go template using the built-in http/template library. I'm finding, though, that if I name the struct's variables with the first letters lowercase, they are not rendered in the template, but if I name them with the first letter uppercase, they are. I see here that structs can have both upper and lower case first letters. Why, then, does the Go templating engine not render both?
For examples, see:
Thanks in advance.
答案1
得分: 4
简单来说,模板引擎无法识别小写字母写的成员,因为模板引擎和你的结构体所在的包不同。
你可能已经注意到,Go语言不使用private
或public
关键字来表示可见性。相反,当标识符的首字母大写时,所有的函数、成员变量等都是公开的。如果标识符没有被导出,它们只能在同一个包中使用。
关于导出标识符的规范:
一个标识符可以被导出以允许从另一个包中访问它。如果满足以下两个条件,标识符就被导出:
- 标识符的名称的第一个字符是一个Unicode大写字母(Unicode类别为"Lu");
- 标识符在包块中声明,或者它是一个字段名或方法名。
所有其他的标识符都不被导出。
英文:
Simply put, the template engine can't see the members when they are written in lower case
as the template engine is in another package than your struct.
You may have noticed that Go does not use private
or public
keywords for visibility.
Instead, all functions, members, variables and the like are public when the first letter
of the identifier is in upper case. If the identifiers are not exported they can only
be used in the same package.
The spec on exporting identifiers:
> An identifier may be exported to permit access to it from another
> package. An identifier is exported if both:
>
> - the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
> - the identifier is declared in the package block or it is a field name or method name.
>
> All other identifiers are not exported.
答案2
得分: 1
这是因为Go模板引擎使用反射来获取它不“知道”的类型的值。只有以大写字母开头的字段名才会被导出,因此可以在反射模型中使用。有关导出和未导出的规则的详细信息,请参见这里:
> [Where..] 标识符名称的第一个字符是一个Unicode大写字母(Unicode类“Lu”)...
还有一些其他的规定,但这是其中最重要的一个。
请参阅这篇文章了解关于Go语言中反射工作原理的一些很好的信息。
英文:
That is because the Go templating engine uses reflection to get the values out of types it doesn't "know" about. Only field names that begin with an uppercase letter are exported – and therefore available to the reflection model. See here for details on the rules of what gets exported and what does not:
> [Where..] the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu")...
There are some other stipulations, but thats the most important one for this.
See this post for some great information on how reflection works in go.
答案3
得分: 0
小写字母在Go中表示私有,因此模板代码不允许访问这些字段。
英文:
lowercase means private in Go so the templating code is not allowed to access the fields.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论