第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

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

1 回答

?
阿波羅的戰(zhàn)車

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

在 Playground 上運行它



查看完整回答
反對 回復(fù) 2023-06-26
  • 1 回答
  • 0 關(guān)注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號