1 回答
TA贡献1862条经验 获得超6个赞
使用偏移量来查找字段:
// getTag returns the tag for a field given a pointer to
// a struct and a pointer to the field in that struct.
func getTag(pv interface{}, pf interface{}) reflect.StructTag {
v := reflect.ValueOf(pv)
offset := reflect.ValueOf(pf).Pointer() - v.Pointer()
t := v.Type().Elem()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Offset == offset {
return f.Tag
}
}
return ""
}
上面的代码假设垃圾收集器不会在对Pointer 的to 调用之间移动结构。这个假设在今天是正确的,但在未来可能并不正确。使用unsafe包使代码能够安全地应对垃圾收集器将来的更改:
// getTag returns the tag for a field with the given offset
// in the struct pointed to by pv.
func getTag(pv interface{}, offset uintptr) reflect.StructTag {
t := reflect.TypeOf(pv).Elem()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Offset == offset {
return f.Tag
}
}
return ""
}
像这样称呼它:
x := MyStruct{}
fmt.Println(getTag(&x, unsafe.Offsetof(x.MyField)))
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报