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

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

通過反射創建結構實例并設置值

通過反射創建結構實例并設置值

Go
滄海一幻覺 2022-10-17 16:14:07
我想做什么我嘗試將instancea 的一個struct- 包括json tags 傳遞給 a func,創建一個新的instance,并在此之后設置value我field嘗試序列化(JSON),但值為空注意:我在 SO 上查找了大量關于通過反射設置值的文章,但似乎我錯過了一些細節結構定義這部分定義了帶有 json 和 xml 標簽的結構type Person struct {    Name string `json:"Name" xml:"Person>FullName"`    Age  int    `json:"Age" xml:"Person>Age"`}創建實例(+包裝成空接口)之后我創建了一個實例并將其存儲在一個interface{}- 為什么?因為在我的生產代碼中,這些東西將在func接受 ainterface{}var iFace interface{} = Person{        Name: "Test",        Age:  666,    }通過反射創建結構的新實例并設置值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)                    }                }            }        }    }問題我究竟做錯了什么?在生產代碼中,我用數據填充多個副本并將其添加到slice...但這只有在s 保持在適當位置并且東西以相同的方式序列化時才有意義。json tag
查看完整描述

1 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

item的類型是reflect.Value. 您必須調用Value.Interface()以獲取包含在其中的值:

fmt.Println("reflected: \n" + JSONify(item.Interface()))

通過此更改,輸出將是(在Go Playground上嘗試):

normal: 

{

    "Name": "Test",

    "Age": 666

}

Name was set to reflectedNameValue

Age was set to 42

reflected: 

{

    "Name": "reflectedNameValue",

    "Age": 42

}

reflect.Value本身也是一個結構,但顯然試圖封送它與封送Person結構值不同。reflect.Value不實現將包裝的數據封送為 JSON。


查看完整回答
反對 回復 2022-10-17
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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