Home Backend Development Golang Detailed explanation of go language structure

Detailed explanation of go language structure

Nov 29, 2019 pm 03:36 PM
go language

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles