For the go language, a magical magic for customizing structure tags.

Source: Internet
Author: User

The case of the first letter in go determines whether this variable can be called externally,

For example, when you use the JSON encoding of a standard library to customize one's structure:

<pre style= "margin-top:0px; margin-bottom:0px; " ><span style= "font-weight:600; Color: #000080; " >package</span><span style= "color: #c0c0c0;" > </span>main

Import(
  "Encoding/json"
  "FMT"
)
TypeTstruct{
 namestring
 Ageint  
}
FuncMain (){
  varinfoT=t{"Fyxichen",   +}
 FMT. Println ("before code:", Info)
 B,_: =json. Marshal (Info)
 FMT. Println ("after encoding:",string(b))
}

The operating result is:

Before encoding: {Fyxichen 24}

After encoding: {"Age": $} Here the value of name is not encoded, because the first letter of the receive is lowercase and external cannot be called.


When we interact with JSON and external APIs, other programming languages do not use casing to control the scope of variables like go. So the use of the following label will be more comfortable.

Package Mainimport ("Encoding/json" "FMT") type T1 struct {name stringage  int}type T2 struct {name string ' JSON: ' Name ' ' Age  int    ' JSON: ' Age ' '}func main () {var info1 T1 = t1{"Fyxichen", 24}var info2 T2 = t2{"Fyxichen", 24}b, _: = json.m Arshal (INFO1) fmt. Println ("Struct1:", string (b)) B, _ = json. Marshal (Info2) fmt. Println ("Struct2:", string (b))}

Operation Result:

Struct1: {"Name": "Fyxichen", "Age": 24}

Struct2: {"name": "Fyxichen", "Age": 24}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

For the go language, a magical magic for customizing structure tags.

Related Article

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.