Home  >  Article  >  Backend Development  >  Embedding application skills of structure type in Golang function

Embedding application skills of structure type in Golang function

WBOY
WBOYOriginal
2023-05-17 08:12:241725browse

Embedding application skills of structure types of Golang functions

Golang is a strongly typed programming language that supports the encapsulation of "objects", which is the definition of structure types. Embedded types can also be used in structure types to extend existing types. In Golang, embedded types actually use the name of a type as a field type in another structure type.

In this article, I will explore the application skills of structure type embedding, specifically, how to use structures with embedded types in Golang functions.

Structure type embedding

There are two main ways to embed structure types in Golang: one is to use the structure type name as an anonymous field, and the other is to use the specified type name as Field name, here we mainly discuss the first method.

When using the structure type name as an anonymous field, the embedded structure will inherit all the fields and methods of the anonymous structure and use them as its own fields and methods. Take a look at the following example:

type Animal struct {
    Name string
    Age  int
}
type Person struct {
    Animal
    Gender string
}

In the above example, we define two structure types Animal and Person, where PersonThe Animal structure type is embedded so that the Person structure can inherit the Name and Age defined in the Animal structure Two fields. In this way, we can access the fields in the Animal structure through the Person structure.

// 构造一个Person类型的对象
p := Person{
    Animal: Animal{
        Name: "Tom",
        Age:  18,
    },
    Gender: "Male",
}
// 访问Animal结构体中的字段
fmt.Println(p.Name, p.Age)

In this example, we define an object of type Person named p and convert the Animal structure type The Name and Age fields are set to "Tom" and 18 respectively. Using the fmt.Println function to output the Name and Age fields of the p object is actually accessing AnimalThe two fields Name and Age in the structure type.

Use structure type embedding to implement "inheritance"

In object-oriented programming, it is often necessary to use the idea of ​​class inheritance to achieve code reuse. Although Golang does not support class inheritance, you can use structure type embedding to achieve some functions similar to class inheritance. The following example uses graphics as an example to demonstrate how to use structure type embedding to implement "inheritance".

type Shape struct {
    Name string
}
func (s *Shape) Draw() {
    fmt.Println("Drawing shape:", s.Name)
}

type Circle struct {
    Shape
    Radius float64
}
func (c *Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

type Rectangle struct {
    Shape
    Length float64
    Width  float64
}
func (r *Rectangle) Area() float64 {
    return r.Length * r.Width
}

In the above example, we defined three structure types: Shape, Circle and Rectangle. Among them, Shape is a base class, Circle and Rectangle are derived classes that implement "inheritance" by embedding the Shape structure type. Using the Shape structure type embedding, the Circle and Rectangle structure types have the member variables and methods of the Shape structure type. .

func main() {
    c := Circle{
        Shape: Shape{"Circle"},
        Radius: 5.0,
    }
    r := Rectangle{
        Shape: Shape{"Rectangle"},
        Length: 10.0,
        Width:  8.0,
    }
    c.Draw()
    r.Draw()
    fmt.Println("Circle area=", c.Area())
    fmt.Println("Rectangle area=", r.Area())
}

In this example, we constructed two objects of type Circle and Rectangle and set their properties respectively. Next, we called the Draw() method to draw these two graphics and calculate their areas.

Note that in the above example, we called the Draw() method of Circle and Rectangle, which is actually calling inheritance. Since the Draw() method of Shape. This is because both the Circle and Rectangle structure types embed the Shape structure type and inherit its methods.

Use structure type embedding to implement the decorator pattern

In software design patterns, the decorator pattern is a structural design pattern that allows you to wrap those instances that need extended functionality. Extend the functionality of objects without limit. In Golang, the decorator pattern can also be easily implemented using structure type embedding.

The following example demonstrates how to implement a simple decorator pattern using structure type embedding.

type Sender interface {
    Send(message string) error
}

type EmailSender struct{}

func (es *EmailSender) Send(message string) error {
    fmt.Println("Email is sending...", message)
    return nil
}

type SmsSender struct{}

func (ss *SmsSender) Send(message string) error {
    fmt.Println("SMS is sending...", message)
    return nil
}

type LoggingSender struct {
    Sender
}

func (ls *LoggingSender) Send(message string) error {
    fmt.Println("Logging...")
    return ls.Sender.Send(message)
}

In the above example, we defined three structure types: EmailSender, SmsSender and LoggingSender. The EmailSender and SmsSender structure types implement the Send() method of the Sender interface. When instances of these two types call their Send() methods, the information "Email is sending..." and "Sms is sending..." will be output respectively.

LoggingSenderThe structure type embeds the Sender interface and overloads the Send() method. LoggingSenderThe Send() method of the structure type adds a statement that outputs "Logging..." and calls the embedded Sender interface at the end. Send() method to complete the specific sending operation. In this way, a simple decorator pattern is implemented, which can add logging functionality when sending messages.

func main() {
    emailSender := &EmailSender{}
    smsSender := &SmsSender{}

    loggingEmailSender := &LoggingSender{Sender: emailSender}
    loggingSmsSender := &LoggingSender{Sender: smsSender}

    loggingEmailSender.Send("Hello, world!")
    loggingSmsSender.Send("Hello, Golang!")
}

在这个例子中,我们创建了一个EmailSender类型和一个SmsSender类型的实例,并且利用LoggingSender类型来装饰它们。我们可以调用装饰后的实例的Send()方法来发送消息,并且会在输出中看到"Logging..."的信息。

结语

本文介绍了Golang中结构体类型嵌入的应用技巧,并以几个简单的实例来说明如何利用嵌入类型实现代码重用、"继承"和装饰器模式等功能。当然,在实际的开发中,结构体类型嵌入还有很多其他的应用场景,需要根据实际需求进行灵活运用。

The above is the detailed content of Embedding application skills of structure type in Golang function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn