反射 – Golang以不同的方式创建结构

伙计们!我是Go的初学者.我有些疑惑当我学习反映包时,这里是代码:

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 {}

为什么这两种方式产生不同的结果,谁能告诉我为什么,非常感谢.

最佳答案 在test2中,您传入包含Test值的接口{}的地址.当json包取消引用该值时,它只会看到一个接口{},因此它会解组为默认类型.

你需要的是一个包含指向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)
点赞