Arrays in Go can store a set of data of the same type, while structures can combine variable data of different types, each of which is a member of the structure.

Creates and initializes a structure

You can create a structure using the following syntax:

type StructName struct{
    field1 fieldType1
    field2 fieldType2
}
Copy the code

Create a structure Employee with firstName, lastName, Salary, and fullTime member variables.

type Empolyee struct{
	firstName string
	lastName string
	salary int
	fullTime bool
}
Copy the code

Member variables of the same type can be placed on one line, so the above code can be abbreviated as:

type Empolyee struct{
	firstName,lastName string
	salary int
	fullTime bool
}
Copy the code

Create a structure variable Ross using the type alias Employee

var ross Empolyee
ross.firstName = "ross"
ross.lastName = "Bingo"
ross.salary = 1000
ross.fullTime = true
fmt.Println(ross)
Copy the code

Output:

{ross Bingo 1000 true}
Copy the code

The above code creates the structure variable Ross and assigns values to each of the member variables. Access the members of a structure using. We can also initialize a structure with a literal:

1Ross := Empolyee{"ross"."Bingo".1000.true} Output: {Ross Bingo1000 true}

2Ross := Empolyee{lastName:"Bingo",
	firstName:"ross",
	salary:1000} Output: {Ross Bingo1000 false}
Copy the code

First, the member variable name is omitted during initialization, but the values of all members must be given in order. Having to remember the types of all members and assign them in order puts an extra burden on the developer and makes the code less maintainable. The second method is recommended, which does not care about the order of the member variables, and assigns values to members that need to be initialized. The default value of unassigned members is the zero value corresponding to the type. Note: Mode 1 and mode 2 initialization modes cannot be used together

ross := Empolyee{
	firstName:"ross",
	lastName:"Bingo".1000,
	fullTime:true,}Copy the code

Mixture of field: Value and Value initializers

The order of the member variables is important for the identity of the structurefirstName,lastNameSwitch the order or willfullTime,salaryThe reverse order defines a different structure type

Structure pointer

When initializing a structure, we can declare a pointer to the structure:

ross_pointer := &Empolyee{
	firstName:"ross",
	lastName:"Bingo",
	salary:1000,
	fullTime:true,}Copy the code

The above code creates a pointer ross_pointer to the Empolyee structure. Members of a structure can be accessed via Pointers:

fmt.Println(*ross_pointer)
fmt.Println("firstName:",(*ross_pointer).firstName)
fmt.Println("firstName:",ross_pointer.lastName)
Copy the code

Output:

{ross Bingo 1000 true}
firstName: ross
firstName: Bingo
Copy the code

Ross_pointer is a struct variable, so (*ross_pointer). FirstName and ross_pointer.lastName are both correct access methods.

Anonymous members

When defining a structure, you can specify only the type of the member instead of the name, and Go will automatically use the type as the name. Members of this structure are called anonymous members. The type of the structure member must be a named type or a pointer to a named type.

type Week struct{
	string
	int
	bool
}
func main(a) {
	week := Week{"Friday".1000.true}
	fmt.Println(week)
}
Copy the code

The above code defines the structure Week, with three member variables, string, int, and bool, that have the same name and type. This can be used in conjunction with the specified member name, for example:

type Empolyee struct{
	firstName,lastName string
	salary int
	bool
}
Copy the code

Structure nesting

Go has structure nesting, where one structure can be a member of another structure type.

type Salary struct {
	basic int
	workovertime int
}

type Empolyee struct{
	firstName,lastName string
	salary Salary
	bool
}

func main(a) {
	ross := Empolyee{
	    firstName:"Ross",
            lastName:"Bingo".bool:true,
            salary:Salary{1000.100},
	}
	fmt.Println(ross.salary.basic);
}
Copy the code

We define a new structure type Salary, change the member type of Empolyee to structure type Salary. Create the Ross structure, and you can still access members in the salary structure by using. For example: Ross.salary.basic. If the structure has too many nested layers and you want to access the innermost member of the structure, using this access method will involve many intermediate variables, resulting in a bloated code. You can simplify this by using the anonymous member approach above. Redefine structure type Empolyee by anonymous member

type Empolyee struct{
	firstName,lastName string
	Salary    // Anonymous member
	bool
}
func main(a) {
	ross := Empolyee{
		firstName:"Ross",
		lastName:"Bingo".bool:true,
		Salary:Salary{1000.100},
	}
	fmt.Println(ross.basic);         // Access mode one
	fmt.Println(ross.Salary.basic);  // Access mode 2
	ross.basic = 1200
	fmt.Println(ross.basic)          // update
}
Copy the code

The above two approaches are equivalent. In this way, the access process is simplified. Note that the nested anonymous structure member cannot have the same name as the previous structure member.

type Empolyee struct{
	firstName,lastName string
	Salary
	basic int
	bool
}
func main(a) {
	ross := Empolyee{
		firstName:"Ross",
		lastName:"Bingo".bool:true,
		Salary{1000.100},
	}
	fmt.Println(ross.basic)
}
Copy the code

In the above code, we modified the structure Empolyee to add a new member with the same name as salary.basic, but the compilation error was: Mixture of field:value and Value initializers

An exportable member

If a variable or function in a Go package starts with a capital letter, the variable or function can be exported. This is the primary access control mechanism for Go. If the member variable name of a structure starts with a capital letter, that member is also exportable. A structure can contain both exportable and non-exportable member variables. In the WORKSPACE path/SRC/org/employee. Go create a package called org, add the following code:

// employee.go
package org
type Employee struct {
	FirstName,LastName string
	salary int
	fullTime bool
}
Copy the code

In the Employee structure, only the variables FirstName and LastName are exportable. Of course, Employee is also exportable. Import org package from main package:

// main.go
package main
import (
	"org"
	"fmt"
)
func main(a) {
	ross := org.Employee{
		FirstName:"Ross",
		LastName:"Bingo",
		salary:1000,     
	}
	fmt.Println(ross)
}
Copy the code

The above code failed to compile because the member variable salary is not extable: unknown field ‘salary’ in struct literal of type org.employee

Since Employee comes from the package org, use org.Employee to create the structure Ross. Type aliasing can be used to simplify:

package main

import (
	"org"
	"fmt"
)

type Employee org.Employee; 

func main(a) {
	ross := Employee{
		FirstName:"Ross",
		LastName:"Bingo",
	}
	fmt.Println(ross)
}
Copy the code

Output:

{Ross Bingo 0 false}
Copy the code

Structural comparison

A structure is comparable if all its members are comparable. You can use == and! =, where == is a member variable that compares two struct variables in order.

type Employee struct {
	FirstName,LastName string
	salary int
	fullTime bool
}
func main(a) {
	ross := Employee{
		FirstName:"Ross",
		LastName:"Bingo",
	}
	jack := Employee{
		FirstName:"Jack",
		LastName:"Lee",
	}
	fmt.Println(ross == jack)
}
Copy the code

Output:

false
Copy the code

Struct variables of different types cannot be compared:

type User struct {
	username string
}
type Employee struct {
	FirstName,LastName string
	salary int
	fullTime bool
}
func main(a) {
	ross := Employee{
		FirstName:"Ross",
		LastName:"Bingo",
	}
	user := User{
		username:"Seekload",
	}
	fmt.Println(ross == user)
}
Copy the code

Invalid operation: Ross == user (mismatched types Employee and user). However, if there are members that are not comparable, such as map, the structure is not comparable.


Original article, if need to be reproduced, please indicate the source! Check out “Golang is coming” or go to seekload.net for more great articles.

The public account “Golang is coming” has prepared a mystery learning gift package for you, and the background replies [ebook] to get it!