vendredi 3 septembre 2021

Reflection to get field tag

In go is there a good way to use reflection to get a field tag by just wrapping a field in a function from the reflect library.

I am basically trying to create a thin data access object that allows be to get the column name in the db without hard coding it all over the place.

Below is the struct with db column names as tags.

    // Table Structures
type CusipTableRow struct {
    Id          int64  `db:"id"`
    Cusip       string `db:"cusip"`
    Symbol      string `db:"symbol"`
    Active      int8   `db:"active"`
    Added_Time  int32  `db:"added_timestamp"`
    Description string `db:"description"`
    Exchange    string `db:"exchange"`
    AssetType   string `db:"asset_type"`
}

Any suggestion other than downloading another library on how to use reflection to essentially make a call like this to return a string with the tag value.

var row CusipTableRow
row.GetColumnName(row.Id) //Return column name based on tag.

I was considering possibly trying to use a map[address] fieldTag, but did not have luck getting that to work perhaps due to not fully having a grasp of the unsafe package. If that approach would have worked I was thinking a call like this could have worked:

row.GetColumnName(&row.Id) //Return column name based on tag.

Any thoughts and suggestions would be great.

Thx





Aucun commentaire:

Enregistrer un commentaire