jeudi 11 août 2022

Go lang strong typed name of a field

I have a go struct that I use to serialize to bson and store in mongodb.

When I make queries, set up indexes, etc very often I need to refer to the field name or the bson tag of it.

Is there a compile time validatable way to do that?

Say if I have the struct:

type Foo struct {
    Bar string `bson:"bar"`
}

then

   query = fmt.SPrintf("%s = 'aaa'", Foo.Bar.GetTag("bson"))

Note I am aware that I can do

   query = fmt.SPrintf("%s = 'aaa'", refect.TypeOf(Foo{}).GetField("Bar").GetTag("bson"))

but that is not what I am looking for. In this last variant if I rename the field Bar to Baz I am not going to get compile time error, because I referred to the name as a string literal.





Aucun commentaire:

Enregistrer un commentaire