1 回答

TA貢獻(xiàn)1862條經(jīng)驗 獲得超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 ""
}
上面的代碼假設(shè)垃圾收集器不會在對Pointer 的to 調(diào)用之間移動結(jié)構(gòu)。這個假設(shè)在今天是正確的,但在未來可能并不正確。使用unsafe包使代碼能夠安全地應(yīng)對垃圾收集器將來的更改:
// 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 關(guān)注
- 163 瀏覽
添加回答
舉報