proposal: x/tools: support for struct field's tag as string const #40247
Labels
FrozenDueToAge
Proposal
Tools
This label describes issues relating to any tools in the x/tools repository.
Milestone
Problem
You can't use string
var / const
in tags. Below is an illegal syntax -As @rsc told in this comment, I also feel tag syntax shouldn't be complicated.
However, this leads us to a situation where we need to carry a
string
(tag) value everywhere in the code. I will try to explain with an example. Below code tries to update auser.Name
field in two different nosql databases. (However this issue remains valid in other scenarios too)Suppose we have a
user
struct as :-Code to update the
user.Name
in MongoDB will be like -Code to update the
user.Name
in ArangoDB will be like -As you can see the problem is -
"ID"
and"NAME"
as string every-time we need to interact with these fields.Problem(1)
Problem(2)
Solution Proposed
In my opinion, there should be single point to manage the field's tag value. Since adding string const inside field's tag value will complicate things, we can go the other way around.
We can have a tool to
go:generate
the tag's value as string constant, and use these constants as the field's tag value.Implementation
This is a very frequent usecase. So I feel, instead of using a third party code, there should be a support in the language tool itself.
If we eventually decide to implement this feature somewhere as a tool, there can be multiple ways to achieve this. At first, to start the discussion, a very raw idea is -
struct_field_tag_const_gen.go
file. This contains all structs'(in the current package) fields' tags as const string in the current package.I have written a very raw code that generates a file with string constants for each package.
It uses
ast.Inspect
andreflect.StructTag
api to access a struct's comments and its fields' tags.It considers only those structs which have some magic comment on it. We can decide what mechanism to follow to filter out the structs. In case we decide this feature worth considering, I'll try to improve my current implementation.
/cc @rsc @alandonovan @mvdan
The text was updated successfully, but these errors were encountered: