Hacker News new | ask | show | jobs
by jerf 3801 days 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.

3 comments

The 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

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.

The value of each key-value pair is documented to be a Go string literal: 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.
A 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