Slice in Go

Source: Internet
Author: User
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{}。

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.