Golang 以不同方式创建结构体

4

大家好!我是一名Go语言的初学者。在学习reflect包时,我有一些疑问。以下是代码:

package main

import (
    "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个回答

2
test2中,您传递了包含Test值的interface{}的地址。当json包对该值进行解引用时,它只看到一个interface{},因此将其取消编组为默认类型。
您需要的是一个包含指向Test值的指针的interface{}
// 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)

非常感谢。我也遇到了这个问题,你的解决方案起作用了! - nagendra547

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接