伙計們!我是 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)
- 1 回答
- 0 關注
- 170 瀏覽
添加回答
舉報
0/150
提交
取消