The methods for defining structure in Go language are: 1. Directly define structure fields; 2. Use embedded structures; 3. Define structures with methods; 4. Use pointer types as structure fields; 5. Use arrays or slices as structure fields. In the Go language, you can use structures to define a set of related fields. These fields can be basic data types, pointer types, array types, slice types, or other structure types. A structure can contain zero or more fields. , and can be customized as needed.
The operating system for this tutorial: Windows 10 system, Go version 1.21, DELL G3 computer.
In the Go language, you can use a structure (struct) to define a set of related fields. These fields can be basic data types, pointer types, array types, slice types or other structure types. A structure can contain zero or more fields and can be customized as needed.
The following are several ways to define structures in Go language:
1. Directly define the structure fields:
type Person struct { Name string Age int }
The above code defines A structure named Person contains two fields Name and Age, which are string type and integer type respectively.
2. Use embedded structures:
You can embed another structure within a structure to combine multiple related fields.
type Student struct { Person // 嵌入结构体 Class string RollNo int }
In the above code, the Student structure is embedded in the Person structure, and also contains two fields: Class and RollNo.
3. Define a structure with methods:
You can define methods for the structure to perform specific operations on the structure. Methods can be implemented by adding method signatures after the structure definition.
type Rectangle struct { Width int Height int } func (r Rectangle) Area() int { return r.Width * r.Height }
In the above code, the Rectangle structure defines two fields Width and Height, and defines a method named Area to calculate the area of the rectangle.
4. Use pointer types as structure fields:
You can include pointer type fields in the structure to store references to other objects in the structure. . Fields of pointer type can be defined using the * symbol.
type Book struct { Title string Author *Person // 指向Person结构体的指针 }
In the above code, the Book structure contains two fields: Title and Author, where Author is a pointer to the Person structure.
5. Use arrays or slices as structure fields:
You can include array or slice type fields in the structure to store a set of elements of the same type. . Fields of array or slice type can be defined using square brackets.
type Queue struct { Items []int // 切片类型的字段 }
The above is the detailed content of What are the methods for defining structures in go language?. For more information, please follow other related articles on the PHP Chinese website!