Home>Article>Backend Development> 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 thego language tutorialcolumn.
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!