gpt4 book ai didi

reflection - Golang 以不同的方式创建结构

转载 作者:IT王子 更新时间:2023-10-29 00:46:18 25 4
gpt4 key购买 nike

伙计们!我是 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 {}

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

最佳答案

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)

关于reflection - Golang 以不同的方式创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com