package main 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) // output:[1,2,3] jsonStr2 := `{"age": 12,"name": "potter", "child":[3,4,5,7,8,9]}` json.Unmarshal([]byte(jsonStr2), &a) fmt.Println(aa) // output: [3,4,5] // fmt.Println(a.Child) // output: [3,4,5,7,8,9] } 解释 type AutoGenerated struct { Child []int } Then you do a := AutoGenerated{} // (1) jsonStr1 := `{"age": 14,"name": "potter", "child":[1,2,3]}` json.Unmarshal([]byte(jsonStr1), &a) // (2) aa := a.Child // (3) fmt.Println(aa) jsonStr2 := `{"age": 12,"name": "potter", "child":[3,4,5,7,8,9]}` json.Unmarshal([]byte(jsonStr2), &a) // (4) fmt.Println(aa) So, what happens: You create a variable, a, of type AutoGenerated which is initialized to the zero value for its type. Because of that, its Child field, which is a slice, is initialized to the zero value……
阅读全文