Golang Reflection: Get Tag from struct field

前端 未结 1 1105
傲寒
傲寒 2021-02-03 21:42

Is it possible to reflect on a field of a struct, and get a reference to its tag values?

For example:

type User struct {
    name    string `json:name-fi         


        
相关标签:
1条回答
  • 2021-02-03 21:56

    You don't need to pass in the whole struct, but passing in the value of one of the fields is not sufficient.

    In your example user.name field is just a string - the reflect package will have no way of correlating that back to the original struct.

    Instead, you need to pass around the reflect.StructField for the given field:

    field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
    …
    tag = string(field.Tag)
    

    Note: we use Elem above because user is a pointer to a struct.

    You can play with an example here.

    0 讨论(0)
提交回复
热议问题