反射以获取字段标记

在 Go 中,有没有一种使用反射的好方法,只需将字段包装在反射库中的函数中即可获取字段标记?


我基本上试图创建一个瘦数据访问对象,该对象允许在数据库中获取列名,而无需到处对其进行硬编码。


下面是将 db 列名称作为标记的结构。


    // 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"`

}

我正在寻找一个建议,而不是下载另一个关于如何使用反射的库来进行这样的调用以返回带有标记值的字符串。


var row CusipTableRow

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

我正在考虑可能尝试使用map[地址]字段标签,但由于没有完全掌握不安全的软件包,因此没有运气使其工作。如果这种方法可行,我想这样的电话可能会起作用:


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


婷婷同学_
浏览 112回答 1
1回答

潇潇雨雨

您可以在给定结构的地址和字段的地址的情况下获取字段标记。不需要不安全的恶作剧。func GetColumnName(pstruct interface{}, pfield interface{}) string {&nbsp; &nbsp; v := reflect.ValueOf(pstruct).Elem()&nbsp; &nbsp; for i := 0; i < v.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if v.Field(i).Addr().Interface() == pfield {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return v.Type().Field(i).Tag.Get("db")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; panic("field not in struct")}使用示例:var v CusipTableRowfmt.Println(GetColumnName(&v, &v.Added_Time)) // prints added_timestamp在Go游乐场上运行它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go