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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置