Search code examples
goreflectgo-structtag

go reflect find by structtag


type A struct {
    Name *NameS `json:"name"`
}

for a struct A,is there a method in reflect that I can find a field by structtag like

reflect.ValueOf(&ns)
// struct
s := ps.Elem()
s.FieldByTag("name")

Solution

  • There is no built-in method/function to do this. The existing FieldBy* methods in reflect are implemented as loops (see `src/reflect/type.go). You can also write a loop to implement what you need here. One approach could be something like:

    func fieldByTag(s interface{}, tagKey, tagValue string) (reflect.StructField, bool) {
        rt := reflect.TypeOf(s)
        for i := 0; i < rt.NumField(); i++ {
            field := rt.Field(i)
            if field.Tag.Get(tagKey) == tagValue {
                return field, true
            }
        }
        return reflect.StructField{}, false
    }
    

    Note that tagKey and tagValue are passed separately because that's how reflect.StructField works. So in your case you'd call it like this:

    field, ok := fieldByTag(&ns, "json", "name")