4 ms·
It is specified - a struct tag is just a string literal after a struct field. See https://golang.org/ref/spec#String_literals https://golang.org/ref/spec#String
by arnehormann 11y ago
It is specified - a struct tag is just a string literal after a struct field. See https://golang.org/ref/spec#String_literals https://golang.org/ref/spec#String_literals
If you use backticks, the tag must not contain another backtick. On anything but a struct tag, you could get by by concatenating literals, but that's not allowed for struct tags: https://golang.org/ref/spec#Tag https://golang.org/ref/spec#Tag You could use double quotes instead of backticks, but that leads to a dark corner of escaping hell and an utterly unreadable mess.
Thankfully, the language strongly nudges you to very, very simplistic and light uses of struct tags.
- jerf 11y ago"It is specified - a struct tag is just a string literal after a struct field." I meant the internals of a struct tag, not the grammar. The standard library implies some structure with things like `json:"name,omit_empty"` but that structure is not actually specified AFAIK. And I seem to recall finding a github issue where the core team said they don't intend to specify one, basically for the reason that they don't want struct tags to be used for things like this systematically, but I couldn't google it up. If they fully "specify" struct tags I think they fear massive metadata additions, instead of little annotations here and there. I'm not quite sure enough of this to state it without qualification, but I am pretty sure it is accurate.
- cypher543 11y agoThe reflect package specifies a "convention" which it uses to extract key-value pairs from a struct tag using the Get method: https://golang.org/pkg/reflect/#StructTag https://golang.org/pkg/reflect/#StructTag There's no need to parse the entire tag string yourself and it's safe to assume other libraries will work with the convention. If they don't, that's not your fault and it would break with other tags like "json" and "xml" anyway.
- arnehormann 11y agoA struct tag is just a string literal - according to the spec. The tags can only be accessed by reflect. The reflect api docs mention the convention. https://golang.org/pkg/reflect/#StructTag https://golang.org/pkg/reflect/#StructTag
- telotortium 11y agoThe value of each key-value pair is documented to be a Go string literal: https://golang.org/pkg/reflect/#StructTag https://golang.org/pkg/reflect/#StructTag. In fact, `strconv.Unquote` is used to convert the value into a string in the code, which agrees with the documentation. In any case, I modified the library in the OP to use a key-value pair and the struct tag `restructure:"\\w+"` works as expected.