Detailed explanation of go language structure

Release: 2019-11-29 15:36:25
forward
2705 people have browsed it

Detailed explanation of go language structure

Definition: It is an aggregated data type, which is an entity aggregated from zero or more values ​​of any type.

Members: Each value is called a member of the structure.

Example:

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

Define structure:

type Employee struct {
    ID        int
    Name      string
    Address   string
    DoB       time.Time
    Position  string
    Salary    int
    ManagerID int
}
Copy after login

Define variables:

var dilbert Employee
Copy after login

Access members:

dilbert.Salary -= 5000
Copy after login

Get the member address:

position := &dilbert.Position
*position = "Senior " + *position
Copy after login

Dot operator and pointer to the structure:

var employeeOfTheMonth *Employee = &dilbert
employeeOfTheMonth.Position += " (proactive team player)"
Copy after login

Member definition order:

Usually one line corresponds to one structure member, and the name of the member comes first and the type comes last. However, if the adjacent member types are the same, they can be merged into one line, just like the Name and Address members below

type Employee struct {
    ID            int
    Name, Address string
    DoB           time.Time
    Position      string
    Salary        int
    ManagerID     int
}
Copy after login

Member naming rules:

If the structure member name starts with a capital letter, then the member is exported; this is determined by the Go language export rules. A structure may contain both exported and unexported members.

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

A structure type named S will no longer contain members of type S: because an aggregate value cannot contain itself. (This restriction also applies to arrays.) But structures of type S can contain members of type *S pointer, which allows us to create recursive data structures, such as linked lists and tree structures.

type tree struct {
    value       int
    left, right *tree
}
Copy after login

Structure face value:

The value of each member can be specified.

type Point struct{ X, Y int }
p := Point{1, 2}
Copy after login

The above is the first way of writing, which requires specifying a face value for each structure member in the order in which the structure members are defined. You can also:

anim := gif.GIF{LoopCount: nframes}
Copy after login

Initialize with member names and corresponding values, which can include some or all members; in this form of structure face value writing, if a member is omitted, it will default to zero value. Since the names of the members are provided, the order in which all members appear is not important.

Note: Two different forms of writing cannot be mixed.

Structure embedding and anonymous members:

type Point struct {
    X, Y int
}

type Circle struct {
    Center Point
    Radius int
}

type Wheel struct {
    Circle Circle
    Spokes int
}
Copy after login

Access each member:

var w Wheel
w.Circle.Center.X = 8
w.Circle.Center.Y = 8
w.Circle.Radius = 5
w.Spokes = 20
Copy after login

Simplified structure definition:

type Circle struct {
    Point
    Radius int
}

type Wheel struct {
    Circle
    Spokes int
}
Copy after login

Proud of anonymous embedding feature, we can access leaf attributes directly without giving the full path:

var w Wheel
w.X = 8            // equivalent to w.Circle.Point.X = 8
w.Y = 8            // equivalent to w.Circle.Point.Y = 8
w.Radius = 5       // equivalent to w.Circle.Radius = 5
w.Spokes = 20
Copy after login

The structure literal must follow the structure when the shape type is declared, so only the following two syntaxes can be used, they are mutually exclusive are equivalent:

w = Wheel{Circle{Point{8, 8}, 5}, 20}

w = Wheel{
    Circle: Circle{
        Point:  Point{X: 8, Y: 8},
        Radius: 5,
    },
    Spokes: 20, // NOTE: trailing comma necessary here (and at Radius)
}
Copy after login

Structure tag:

In the structure declaration, the string face value after the Year and Color members is the structure member Tag

type Movie struct {
    Title  string
    Year   int  `json:"released"`
    Color  bool `json:"color,omitempty"`
    Actors []string
}

var movies = []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"}},
    // ...
}
Copy after login

like this The data structure is particularly suitable for the JSON format, and it is easy to convert between the two. The process of converting a slice, a structure similar to movies in the Go language, to JSON is called marshaling. Marshaling is done by calling the json.Marshal function:

data, err := json.Marshal(movies)
if err != nil {
    log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
Copy after login

The Marshal function returns an encoded byte slice containing a long string without white space indentation; we wrap it for display:

[{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingr
id Bergman"]},{"Title":"Cool Hand Luke","released":1967,"color":true,"Ac
tors":["Paul Newman"]},{"Title":"Bullitt","released":1968,"color":true,"
Actors":["Steve McQueen","Jacqueline Bisset"]}]
Copy after login

Among them, the member of the Year name became released after encoding, and the Color member became color starting with a lowercase letter after encoding. This is caused by the conformation member Tag. A structure member Tag is a string of metainformation associated with the member during the compilation phase:

Year  int  `json:"released"`
Color bool `json:"color,omitempty"`
Copy after login

The member Tag of the structure can be any string literal value, but is usually a series of keys separated by spaces. :"value" sequence of key-value pairs; because the value contains double quote characters, member tags are generally written in the form of native string literals.

For more go language knowledge, please pay attention to the go language tutorial column.

The above is the detailed content of Detailed explanation of go language structure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template