亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不使用字段名稱作為字符串的情況下獲取字段的標簽?

如何在不使用字段名稱作為字符串的情況下獲取字段的標簽?

Go
慕哥6287543 2023-06-26 16:46:00
是否可以使用僅接收結構和字段本身的函數來獲取字段標記?我知道我可以做這樣的事情:reflect.TypeOf(x).FieldByName("FieldNameAsString").Tag但在這種情況下,我不想使用字段的名稱作為字符串,因為它將來可能會被重命名,所以最好使用字段本身。type MyStruct struct {    MyField string `thetag:"hello"`}func main() {    x := MyStruct{}    getTag(x, x.MyField)}
查看完整描述

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)))

在 Playground 上運行它。



查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號