GO language Structure

Source: Internet
Author: User
Tags uppercase letter
This is a creation in Article, where the information may have evolved or changed.

Defined:

is an aggregated data type that is an entity that is aggregated by 0 or more values of any type.

Members:

Each value is called a member of the struct.

Example:

Use the structure of the classic case of the company's employee information, each employee information contains a unique employee number, employee name, home address, date of birth, job, salary, superior leadership and so on. All of this information needs to be bound to an entity, which can be copied as a whole unit, as a function parameter or return value, or stored in an array, and so on.

Define the structure body:

struct {    ID        int    Name      string    Address      String    DoB time       . Time    Position  string    Salary     int     int }

Define variables:

var Dilbert Employee

Access Members:

5000

Fetch member Address:

Position: = &Dilbert. Position"" + *position
Point operators and pointers to struct bodies:
var employeeofthemonth *employee = &"  (Proactive team player)"

Member Definition Order:

Usually a row corresponds to a struct member whose name is in the previous type, but if the adjacent member type is the same, it can be merged into a single row, as in the following name and address member

struct {    ID            intstring        DoB time           . Time    Position      string    Salary        int    ManagerID      int }

Member naming rules:

If the struct member name starts with an uppercase letter, then the member is exported, which is determined by the Go language export rule. A struct may contain both exported and non-exported members.

Export meaning: Can be read and written in other packages.

A struct type named S will no longer contain members of type S: because an aggregated value cannot contain itself. (The restriction also adapts to arrays.) However, the struct of type S can contain *S members of the pointer type, which allows us to create recursive data structures such as linked lists and tree structures.

struct {    value       int*    Tree}

struct face value:

You can specify a value for each member.

struct int }p:= point{12}
The above is the first notation, which requires that each struct member be given a face value in the order defined by the struct member. It's OK:
ANIM: = gif. Gif{loopcount:nframes}

Initialized with a member's name and corresponding value, which can contain some or all of the members, and in this form, if the member is ignored, the default value is 0. Because, given the name of the member, the order in which all members appear is not important.

Note: Two different forms of writing cannot be used in combination.

struct embedding and anonymous members:

struct {     intstruct   {    Center    point int  struct  {    Circle circle    int}

To access each member:

var8 8 5

In the secondary simplified structure definition:

struct      {point    int struct {Circleint      }

Proud of the anonymous embedding feature, we can directly access the leaf properties without having to give the full path:

var8            //  equivalent to W.circle.point.x = 88            // equivalent to W.circle.point.y = 8 5       // equivalent to W.circle.radius = 5  -

struct literals must conform to the structure of the shape type declaration, so you can use only the following two syntaxes, which are equivalent to each other:

w = wheel{circle{point{885= wheel{    circle:circle{        Point:  88},        5,    },     // note:trailing comma necessary here (and at Radius)}

Structure tag:

In a struct declaration, the string value following the year and the color member is the struct member tag

Type Moviestruct{Titlestring Yearint' JSON:"released"' ColorBOOL' JSON:"Color,omitempty"' Actors []string}varMovies =[]movie{{Title:"Casablanca", Year:1942, Color:false, Actors: []string{"Humphrey Bogart","Ingrid Bergman"}}, {Title:"Cool Hand Luke", Year:1967, Color:true, Actors: []string{"Paul Newman"}}, {Title:"Bullitt", Year:1968, Color:true, Actors: []string{"Steve McQueen","Jacqueline Bisset"}},    // ...}

Such data structures are particularly well-suited for JSON formats and are easy to convert between the two. The process of converting a movies-like structure in a go language slice to JSON is called marshalling (marshaling). GROUP by calling JSON. The Marshal function is complete:

Data, err: = json. Marshal (Movies)if err ! = nil {    log. Fatalf ("JSON marshaling failed:%s", Err)}fmt. Printf ("%s\n", data)

The marshal function returns an encoded byte slice, contains a long string, and has no blank indentation; we wrap it to make it easier to display:

[{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","IngrID Bergman"]},{"Title":"Cool Hand Luke","Released": 1967,"Color": True,"Actors":["Paul Newman"]},{"Title":"Bullitt","Released": 1968,"Color": True,"Actors":["Steve McQueen","Jacqueline Bisset"]}]
The members of year names become released after encoding, and color members are encoded into a color that starts with a lowercase letter. This is due to the structure member tag. A structure member tag is a meta-information string that is associated with the member during the compile phase:
Year  int  ' json:"released"bool ' JSON:"  color,omitempty"'

The member tag of a struct can be any string literal, but it is usually a series of keys separated by spaces: the "value" key-value pair sequence, because the value refers to a double-quote character, so the member tag is generally written in the form of a native string value.

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.