SoFunction
Updated on 2025-03-01

Detailed explanation of the characteristics of structures in Go language

1. Introduction

Structures are one of the important and flexible concepts in the Go language. The use of structures allows us to define our own data types and combine different types of fields together to achieve more flexible data structures. This article aims to introduce structures in Go in depth, reveal their importance and flexibility, and show readers the many features supported by structures and demonstrate their power.

2. What is a structure

In Go, a structure is a custom data type used to combine different types of fields together to form a new data structure. A structure defines a set of fields, each field can have a different type, and these fields together form an instance of the structure. Through structures, we can organize and manage relevant data, so that it can be operated and transmitted more easily.

The definition of the structure uses the keyword type and struct. The following is the definition syntax for the structure:

type structure name struct {
Field 1 Type 1
Field 2 Type 2
// More fields...
}

In the above syntax, the structure name is the name we give to the structure type, and can be named according to the actual situation. The field part of the structure lists all the fields contained in the structure, and each field has a field name and corresponding field type. Below we give an example of the structure definition:

type User struct {
    Name string
    Age  int
    Address string
}

The structure defines a structure type named User, which contains two fields: Name and Age, whose types are strings and integers respectively. So far, we have completed a basic introduction to the structure and can create a new data type based on it.

However, the definition of a structure only creates a new data type. Using a structure requires creating its instance. Several instantiation methods are provided in the Go language, which we will explain in detail below.
First, you can use the structure literal to directly initialize the structure variables and give the corresponding values ​​in the order of the fields. Examples are as follows:

person := Person{"Alice", 25, "Guangdong Shenzhen"}

Secondly, the initialization value of the field can be given by specifying the field name. At this time, some fields can be ignored. Examples are as follows:

person := Person{Name: "Alice", Age: 25}

You can also use the new keyword to create a pointer to the structure and return that pointer. Examples are as follows:

personPtr := new(Person)
 = "Alice"
 = 25

Or use the var keyword to declare structure variables and then assign values ​​to fields respectively. Examples are as follows:

var person Person
 = "Alice"
 = 25

The above are common structure instantiation and initialization methods, and choose the appropriate method according to actual needs. Either way, you can create and initialize an instance of a structure for subsequent use and manipulation of the structure's fields.

So far, we have introduced what a structure is. In fact, a structure can be considered a combination of a set of different types of fields and used to represent a new concept. Secondly, we also introduced several ways to instantiate custom structures. Based on this, we have a rough understanding of structures.

3. What characteristics does the structure support?

We have a basic understanding of structures above. Structures can combine a set of different types of fields to represent a new concept. However, the structure does not stop there, and it also supports definition methods, data encapsulation, etc. Through these characteristics, structures are flexible, extensible and readable in the Go language, and play an important role in object-oriented programming, data modeling, and code reuse.

3.1 Structure support definition method

Structures support defining methods in Go language, which are functions associated with structures. This feature allows us to correlate specific behaviors and functions with structures and operate the structure's data through methods.
Here is an example that demonstrates the characteristics of structures that support definition methods:

package main
import "fmt"
// Define structuretype Person struct {
    Name string
    Age  int
}
// Definition method: Print personal informationfunc (p Person) PrintInfo() {
    ("Name: %s\n", )
    ("Age: %d\n", )
}
// Definition method: Modify agefunc (p Person) UpdateAge(newAge int) {
     = newAge
}
func main() {
    // Create a Person structure instance    person := Person{Name: "John", Age: 30}
    // How to call structure: Print personal information    () // Output: Name: John   Age: 30
    // Call the structure method: modify age    (35)
    // Call the method again to print the modified personal information    () // Output: Name: John   Age: 35
}

In the above code, we define a Person structure that contains two fields Name and Age. We then define two methods for the structure: PrintInfo() and UpdateAge().

In the main() function, we create a Person structure instance person, and call two methods through this instance: PrintInfo() and UpdateAge(). First, we call the PrintInfo() method to print out the initial personal information. Then, we call the UpdateAge() method and change the age to 35. Finally, we call the PrintInfo() method again to print the modified personal information.

Through the structure definition method, we can encapsulate structure-related data and operations together, improving the readability and maintainability of the code. The method can directly access the fields of the structure and operate on them, making the code more concise and clear.

3.2 Settings of structures that support data visibility

Structures support data visibility in Go language. It can limit the visibility of structure fields and methods through initial case, thereby achieving hiding and encapsulation of information.

In a structure, the method name or field name, whose initial letter is capitalized, means that it is visible and modifiable to the outside; the initial letter is lowercase, means that it is invisible to the outside. If you want to read or modify it, you can only do it through an exposed interface. In this way, the internal implementation details of the structure can be hidden, while ensuring that access and operation of the structure data is carried out through the encapsulation public method, providing better security and encapsulation. Here is an example of code:

package main
import "fmt"
// Define structuretype Person struct {
    name string // Private fields}
// Define the public method: Set the namefunc (p *Person) SetName(name string) {
     = name
}
// Define the public method: get the namefunc (p *Person) GetName() string {
    return 
}
func main() {
    // Create a Person structure instance    person := Person{}
    // It will not be possible to compile here    //  = "hello eva"
    // Set name and age through public method    ("John")
    // Get the name and age through public method and print it    ("Name:", ()) // Output: Name: John
}

In the above code, we define a Person structure that contains the private field name. Then, we define two public methods GetName() and SetName() for the structure, which can set and read the value of the private field name field respectively.

If the name field is read directly through the structure instance person, the compilation will not be possible at this time. In this way, it is ensured that access and operation of structure data are carried out through the disclosed method of encapsulation, providing better security and encapsulation.

3.3 Structure can implement interfaces

The interface defines a contract for a set of methods that describes the behavior and signature of these methods.

In Go, an interface is a type consisting of a set of method signatures. A structure can implement all methods in the interface, which can be considered to implement the interface, so that it can be used in the same way. This feature provides polymorphism, allowing us to write common code that works well for many types of structures. Here is an example that demonstrates how a structure implements an interface:

package main
import "fmt"
// Define the interfacetype Shape interface {
    Area() float64
    Perimeter() float64
}
// Define rectangular structuretype Rectangle struct {
    Width  float64
    Height float64
}
// Implement the interface method: calculate the area of ​​the rectanglefunc (r Rectangle) Area() float64 {
    return  * 
}
// Implement the interface method: calculate the perimeter of the rectanglefunc (r Rectangle) Perimeter() float64 {
    return 2 * ( + )
}
func main() {
    // Create a rectangular structure instance    rectangle := Rectangle{Width: 5, Height: 3}
    // Assign rectangle instance to interface variable    var shape Shape
    shape = rectangle
    //Calculate the area and perimeter through the interface    area := ()
    perimeter := ()
    ("Area:", area)           // Output: Area: 15
    ("Perimeter:", perimeter) // Output: Perimeter: 16
}

In the above code, we define an interface Shape, which contains the signatures of two methods: Area() and Perimeter(). We then define a rectangle structure, Rectangle, and implement the methods defined in the interface Shape for that structure.

In the main() function, we create a rectangle instance of the rectangle. Then, we assign the rectangle instance to the interface type variable shape, because the rectangle structure implements the Shape interface, it can be assigned to the interface variable.

Next, we call the Area() and Perimeter() methods through the interface variable shape, which actually calls the corresponding methods on the rectangular structure. Through the call method of interfaces, we can operate on different structure types in a unified way without caring about specific types.

The characteristics of this structure implementation interface provide support for polymorphism, allowing us to write general code that is suitable for many types of structures. It makes the code more flexible, scalable, and better cope with changes in demand.

3.4 Structure support combination

Structures support the combination feature, and code reuse and combination are realized by embedding other structures as fields. Doing so allows the external structure to directly access the fields and methods of the embedded structure, thereby multiplexing the functions of the internal structure.

Specifically, by embedding other structures as anonymous fields in the external structure, we can directly access the fields and methods of the internal structure without explicit delegating or wrapping. Here is an example that demonstrates the characteristics of structures supporting combinations:

package main
import "fmt"
// Define the infrastructuretype Person struct {
        Name string
        Age  int
}
// Define the extended structure and embed the infrastructure structuretype Employee struct {
        Person     // Anonymous field, embedded in Person structure        EmployeeID int
}
func main() {
        // Create an Employee structure instance        employee := Employee{
                Person: Person{
                        Name: "John",
                        Age:  30,
                },
                EmployeeID: 12345,
        }
        // Access fields and methods of internal structures        ("Name:", ) // Output: Name: John
        ("Age:", )   // Output: Age: 30
}

In the above code, we define two structures: Person and Employee. Employee structures are combined by embedding Person structures as an anonymous field.

Through combination, the Employee structure can directly access fields Name and Age embedded in the field Person. In the main() function, we create an Employee structure instance employee and can directly access the fields of its internal structure Person.

By combining, we can reuse fields and methods in other structures to avoid repeated writing of the same code. This can improve the reusability and maintainability of the code. Secondly, the combination also provides a flexible way to extend the function of the structure. We can embed the interface type as a field, and different implementations can be used in different scenarios, making the entire design more flexible.

The structure supports combination characteristics, which greatly enhances the expressiveness of the Go language, allowing us to better organize and manage code and achieve more flexible and scalable programming.

3.5 Structure tag support

Structure support setting tags is a feature provided by Go. Tags are metadata attached to the structure field as strings to provide additional information and configuration. This feature is supported by the Go language compiler and related libraries, and also follows the standard format defined by the Go language.

The format of the structure tag is key:"value", which can contain one or more key-value pairs, separated by spaces. The tag is in the backtick marks of the field declaration, for example:

type Person struct {
        Name string `json:"name" db:"full_name"`
        Age  int    `json:"age" db:"age"`
}

In Go language, structure tags have played a very important role in many scenarios. It contains serialization and deserialization of structures, database mapping, form verification, etc. Below we will briefly explain it through a serialized scenario, and will explain more detailed content later.

type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
}
func main() {
        p := Person{Name: "John Doe", Age: 30}
        data, _ := (p)
        (string(data)) // Output: {"name":"John Doe","age":30}
}

In the above example, by setting the json tag of the field, we can specify the field name when JSON is serialized so that the generated JSON string conforms to the expected format.

Here, the setting of the structure tag can provide more metadata and configuration information, making the code more readable, maintainable and flexible. At the same time, the parsing and application of tags are performed at runtime, allowing us to flexibly configure and adjust the behavior of structure fields when writing code without modifying the code itself, which provides greater flexibility and convenience.

3.6 Feature Summary

In Go, structures are a powerful and flexible data type that supports the definition of methods and can also implement interfaces, combinations and visibility settings.

The combination of these features makes the structures in the Go language very powerful and flexible. Users can use structures to define their own data types and define methods and behaviors for them. At the same time, structures can be used with interfaces to achieve polymorphism and code reuse. Combination and visibility settings of structures provide a higher level of abstraction and encapsulation capabilities, making the code more extensible and maintainable.

At the same time, the structure also defines a set of label rules, which can use labels to add metadata to fields, which enhances the function and expressiveness of the code, and improves the scalability and reusability of the code in terms of annotation, serialization, checksum mapping, etc.

4. Summary

In this article, we first start with the definition of the structure, clarify how to define the structure, and introduce four instantiation methods of the structure. Through these basic knowledge, we have a basic understanding of structures.

Next, we discuss in detail several important features of structure support. We introduce the ability of structures to support definition methods, allowing us to add custom behavior to structures. We also learned how to support data visibility settings for structures to protect data security through access control. We also introduce that structures can implement interfaces, so that structures can meet the requirements of interfaces and achieve more flexible code organization and abstraction. Finally, we also talk about the characteristics of structures supporting combination, allowing us to combine multiple structures into a larger structure to achieve code reuse and combinatoriality.

To sum up, this article comprehensively introduces the definition and instantiation methods of structures, and explains in detail the various characteristics supported by structures. Based on the above content, we have completed the introduction of the Go language structure, and I hope it will be helpful to you.

This is the end of this article about explaining the characteristics of structures in Go. For more related contents of Go structures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!