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

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

Golang 以不同的方式創建結構體

Golang 以不同的方式創建結構體

Go
慕少森 2021-12-07 14:19:38
伙計們!我是 Go 的初學者。當我學習reflect包時,我有一些疑問,這是代碼:package mainimport (    "encoding/json"    "fmt"    "reflect")func checkError(err error) {    if err != nil {        panic(err)    }}type Test struct {    X int    Y string}func main() {    fmt.Println("hello world!")    test1()    test2()}func test1() {    a := Test{}    fmt.Printf("a: %v %T \n", a, a)    fmt.Println(a)    err := json.Unmarshal([]byte(`{"X":1,"Y":"x"}`), &a)    checkError(err)    fmt.Printf("a: %v %T \n", a, a)}func test2() {    fmt.Println("===========================")    m := make(map[string]reflect.Type)    m["test"] = reflect.TypeOf(Test{})    a := reflect.New(m["test"]).Elem().Interface()    fmt.Printf("a: %v %T \n", a, a)    fmt.Println(a)    err := json.Unmarshal([]byte(`{"X":1,"Y":"x"}`), &a)    checkError(err)    fmt.Printf("a: %v %T \n", a, a)}結果:a: {0 } main.Test {0 }a: {1 x} main.Test ===========================a: {0 } main.Test {0 }a: map[X:1 Y:x] map[string]interface {}為什么這兩種方式會產生不同的結果,誰能告訴我為什么,非常感謝。
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

在test2您傳入interface{}包含Test值的地址。當 json 包取消引用該值時,它只會看到一個interface{},因此它會解組為默認類型。


您需要的是一個interface{}包含指向Test值的指針。


// reflect.New is creating a *Test{} value.

// You don't want to dereference that with Elem()

a := reflect.New(m["test"]).Interface()


// 'a' contains a *Test value. You already have a pointer, and you

// don't want the address of the interface value.

err := json.Unmarshal([]byte(`{"X":1,"Y":"x"}`), a)


查看完整回答
反對 回復 2021-12-07
  • 1 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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