doubi3996 2014-05-24 01:17
浏览 30
已采纳

如何读取struct字段装饰器?

My package needs to be able to let my users define the fields backend database column name explicitly, if they want to.

By default I will use the fields name - but sometimes they will need to manually specify the column name, just like the JSON package - unmarshal uses the explicit name if required.

How can I consume this explicit value in my code? I don't even know what it's called so Google is really failing me at the moment.

Here's what JSON's unmarshal function needs for example:

type User struct {
    Name string
    LastName    string  `json:"last_name"`
    CategoryId  int     `json:"category_id"`
}

What would I need to use something like this?

// Paprika is my package name.
type User struct {
    Name string
    LastName    string   `paprika:"last_name"`
    CategoryId  int      `paprika:"category_id"`
}

My package will be constructing SQL queries and I can't just rely on the field's name - I need to be able to let them manually set the column name. So this is working with only the defined columns at the moment.

// Extracts resource information using reflection and
// saves field names and types.
func loadTypeToSchema(resource interface{}) {
    resourceType := reflect.TypeOf(resource)

    // Grab the resource struct Name.
    fullName := resourceType.String()
    name := fullName[strings.Index(fullName, ".")+1:]

    // Grabs the resource struct fields and types.
    fieldCount := resourceType.NumField()
    fields := make(map[string]string)
    for i := 0; i <= fieldCount-1; i++ {
        field := resourceType.Field(i)
        fields[field.Name] = field.Type.Name()
    }

    // Add resource information to schema map.
    schema[name] = fields
}
  • 写回答

1条回答 默认 最新

  • dongshi6969 2014-05-24 01:27
    关注

    First of all, what you call decorators are actually called tags. You can read these tags using reflection. The reflect package even has its own example for that.

    Nevertheless, here's another example that prints all tags of the members of a struct (Click to play):

    type Foo struct {
        A int `tag for A`
        B int `tag for B`
        C int
    }
    
    func main() {
        f := Foo{}
        t := reflect.TypeOf(f)
    
        for i := 0; i < t.NumField(); i++ {
            fmt.Println(t.Field(i).Tag)
        }
    }
    

    Note that in case f is a pointer, e.g. a *Foo, you'd have to indirect (dereference) that value first or else the type returned by TypeOf is not a struct but a pointer and NumField as well as Field() would not work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。