This is a created
article in which the information may have evolved or changed.
Recently, when writing code, you need to call JSON. The Marshal () function parses the data of the struct type into JSON format. But the value of the field that was found and changed after the modification was empty, that is, [] and now it becomes null. After the hundred think, finally understood the reason.
First, the conclusion:
The slice format data in go, the JSON is called when there is no initialization. The Marshal () function becomes null, and after initialization the slice is parsed into [].
For example:
package mainimport ( "encoding/json" "fmt")type A struct { Numbers []int}func main() { var R = A{} R.Numbers = make([]int, 0) s, _ := json.Marshal(R) fmt.Printf("%s\n", s) var R1 = A{} s1, _ := json.Marshal(R1) fmt.Printf("%s\n", s1)}
The result of the operation is:
{"Numbers":[]}{"Numbers":null}
The reason for this result is that the numbers in the struct has not been initialized.
var s []intands := make([]int, 0)
Slice can be initialized in two ways: one iss := make([]int, 0),一种是 s := []int{}。