我想做什么我嘗試將instancea 的一個(gè)struct- 包括json tags 傳遞給 a func,創(chuàng)建一個(gè)新的instance,并在此之后設(shè)置value我field嘗試序列化(JSON),但值為空注意:我在 SO 上查找了大量關(guān)于通過(guò)反射設(shè)置值的文章,但似乎我錯(cuò)過(guò)了一些細(xì)節(jié)結(jié)構(gòu)定義這部分定義了帶有 json 和 xml 標(biāo)簽的結(jié)構(gòu)type Person struct { Name string `json:"Name" xml:"Person>FullName"` Age int `json:"Age" xml:"Person>Age"`}創(chuàng)建實(shí)例(+包裝成空接口)之后我創(chuàng)建了一個(gè)實(shí)例并將其存儲(chǔ)在一個(gè)interface{}- 為什么?因?yàn)樵谖业纳a(chǎn)代碼中,這些東西將在func接受 ainterface{}var iFace interface{} = Person{ Name: "Test", Age: 666, }通過(guò)反射創(chuàng)建結(jié)構(gòu)的新實(shí)例并設(shè)置值iFaceType := reflect.TypeOf(iFace) item := reflect.New(iFaceType) s := item.Elem() if s.Kind() == reflect.Struct { fName := s.FieldByName("Name") if fName.IsValid() { // A Value can be changed only if it is // addressable and was not obtained by // the use of unexported struct fields. if fName.CanSet() { // change value of N switch fName.Kind() { case reflect.String: fName.SetString("reflectedNameValue") fmt.Println("Name was set to reflectedNameValue") } } } fAge := s.FieldByName("Age") if fAge.IsValid() { // A Value can be changed only if it is // addressable and was not obtained by // the use of unexported struct fields. if fAge.CanSet() { // change value of N switch fAge.Kind() { case reflect.Int: x := int64(42) if !fAge.OverflowInt(x) { fAge.SetInt(x) fmt.Println("Age was set to", x) } } } } }問(wèn)題我究竟做錯(cuò)了什么?在生產(chǎn)代碼中,我用數(shù)據(jù)填充多個(gè)副本并將其添加到slice...但這只有在s 保持在適當(dāng)位置并且東西以相同的方式序列化時(shí)才有意義。json tag
通過(guò)反射創(chuàng)建結(jié)構(gòu)實(shí)例并設(shè)置值
滄海一幻覺(jué)
2022-10-17 16:14:07