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 }
Define variables:
var dilbert Employee
Access members:
dilbert.Salary -= 5000
Get the member address:
position := &dilbert.Position *position = "Senior " + *position
Dot operator and pointer to the structure:
var employeeOfTheMonth *Employee = &dilbert employeeOfTheMonth.Position += " (proactive team player)"
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 }
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 }
Structure face value:
The value of each member can be specified.
type Point struct{ X, Y int } p := Point{1, 2}
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}
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 }
Access each member:
var w Wheel w.Circle.Center.X = 8 w.Circle.Center.Y = 8 w.Circle.Radius = 5 w.Spokes = 20
Simplified structure definition:
type Circle struct { Point Radius int } type Wheel struct { Circle Spokes int }
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
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) }
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"}}, // ... }
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)
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"]}]
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"`
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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. �...

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 well-known open source projects? When programming in Go, developers often encounter some common needs, ...

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? When using GoLand for Go language development, many developers will encounter custom structure tags...

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...

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...
