jhnnycrvr
jhnnycrvr

Reputation: 817

Struct Variable Names in Go Templates

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.

Upvotes: 2

Views: 2965

Answers (3)

J. Holmes
J. Holmes

Reputation: 18546

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.

Upvotes: 1

nemo
nemo

Reputation: 57609

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.

Upvotes: 5

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657118

lowercase means private in Go so the templating code is not allowed to access the fields.

Upvotes: 0

Related Questions