json解析与slice

import (
 "encoding/json"
 "fmt"
)

type AutoGenerated struct {
 Age   int    `json:"age"`
 Name  string `json:"name"`
 Child []int  `json:"child"`
}

func main() {
 jsonStr1 := `{"age": 14,"name": "potter", "child":[1,2,3]}`
 a := AutoGenerated{}
 json.Unmarshal([]byte(jsonStr1), &a)
 aa := a.Child
 fmt.Println(aa)
 jsonStr2 := `{"age": 12,"name": "potter", "child":[3,4,5,7,8,9]}`
 json.Unmarshal([]byte(jsonStr2), &a)
 fmt.Println(aa)
}

第一感觉是,程序会输出

[1 2 3]
[3 4 5 7 8 9]

然而正确的答案是

[1 2 3]
[3 4 5]

这道题关键的坑,其实是在 aa := a.Child ,变量 aa 实质是 一个长度为3,容量为4的切片;
然而,要将一个 JSON 数组解码到切片(slice)中,Unmarshal 将切片长度重置为零,然后将每个元素 append 到切片中。特殊情况,如果将一个空的 JSON 数组解码到一个切片中,Unmarshal 会用一个新的空切片替换该切片,由于是append,所以 a.child 切片的长度、容量也会跟随发生改变。

在第二次打印 aa 时,由于其底层数组 变为 【3 4 5 7 8 9】,且aa长度为3,所以会输出【3 4 5】

原文地址:https://www.cnblogs.com/fanzou/p/13877609.html