php小編百草為你帶來(lái)了一篇關(guān)于Golang的文章,標(biāo)題是“解組動(dòng)態(tài) YAML 注釋”。這篇文章將詳細(xì)介紹如何在Golang中解析包含注釋的YAML文件,并將注釋信息與對(duì)應(yīng)的數(shù)據(jù)關(guān)聯(lián)起來(lái)。通過(guò)本文,你將了解到如何使用Go語(yǔ)言的yaml.v3包來(lái)實(shí)現(xiàn)這一功能,并能夠在自己的項(xiàng)目中靈活應(yīng)用。無(wú)論你是初學(xué)者還是有一定經(jīng)驗(yàn)的開(kāi)發(fā)者,這篇文章都將為你提供有價(jià)值的知識(shí)和技巧。讓我們一起開(kāi)始吧!
問(wèn)題內(nèi)容
我想動(dòng)態(tài)更改 struct
的注釋并使用 yaml.unmarshal
,如下所示:
package main import ( "fmt" "reflect" "gopkg.in/yaml.v3" ) type User struct { Name string `yaml:"dummy"` } func (u *User) UnmarshalYAML(node *yaml.Node) error { value := reflect.ValueOf(*u) t := value.Type() fields := make([]reflect.StructField, 0) for i := 0; i < t.NumField(); i++ { fields = append(fields, t.Field(i)) if t.Field(i).Name == "Name" { fields[i].Tag = `yaml:"name"` // Dynamic annotation } } newType := reflect.StructOf(fields) newValue := value.Convert(newType) err := node.Decode(newValue.Interface()) // Cause error because it's not pointer return err } var dat string = `name: abc` func main() { out := User{} yaml.Unmarshal([]byte(dat), &out) fmt.Printf("%+v\n", out) }
登錄后復(fù)制
它會(huì)導(dǎo)致像 panic:reflect:reflect.value.set using unaddressable value [recovered]
這樣的錯(cuò)誤,我認(rèn)為這是因?yàn)?node.decode
不與指針一起使用。那么如何創(chuàng)建新類型的指針呢?
解決方法
這是有效的更新演示:
package main import ( "fmt" "reflect" "unsafe" "gopkg.in/yaml.v3" ) type User struct { Name string `yaml:"dummy"` } func (u *User) UnmarshalYAML(node *yaml.Node) error { t := reflect.TypeOf(*u) fields := make([]reflect.StructField, 0) for i := 0; i < t.NumField(); i++ { fields = append(fields, t.Field(i)) if t.Field(i).Name == "Name" { fields[i].Tag = `yaml:"name"` // Dynamic annotation } } newType := reflect.StructOf(fields) newValue := reflect.NewAt(newType, unsafe.Pointer(u)).Elem() err := node.Decode(newValue.Addr().Interface()) return err } var dat string = `name: abc` func main() { out := User{} yaml.Unmarshal([]byte(dat), &out) fmt.Printf("%+v\n", out) }
登錄后復(fù)制
兩個(gè)關(guān)鍵變化:
將 newvalue.interface()
替換為 newvalue.addr().interface()
。 (參見(jiàn)此示例:https://www.php.cn/link/e96c7de8f6390b1e6c71556e4e0a4959 a>)
將 newvalue := value.convert(newtype)
替換為 newvalue := reflect.newat(newtype, unsafe.pointer(u)).elem()
。
我們這樣做是因?yàn)?value :=reflect.valueof(*u)
中的 value
是不可尋址的(您可以使用 fmt.printf("%v", value.addr())
進(jìn)行驗(yàn)證。它會(huì)出現(xiàn)錯(cuò)誤并顯示消息 panic : 不可尋址值的reflect.value.addr(
)。