How to inherit in golang

王林
Release: 2023-05-22 15:25:07
Original
879 people have browsed it

In the Go language, there is no "class" defined in traditional object-oriented languages, so there is no so-called "inheritance". However, the Go language provides a method to achieve similar inheritance through composition, called Embedding.

Embedding allows us to embed a type into another type, so that the embedded type can directly access the properties and methods of the type in which it is embedded without having to access it through an interface or other means. This process is similar to traditional "inheritance", but more flexible.

Below, we will use several examples to demonstrate how to use embedding to achieve inheritance-like functions.

  1. Basic example

We first define a few basic structures, dogs, cats and people:

type Dog struct {
    name string
}

func (d Dog) Bark() {
    fmt.Println(d.name, ": 汪汪汪!")
}

type Cat struct {
    name string
}

func (c Cat) Mew() {
    fmt.Println(c.name, ": 喵喵喵!")
}

type Person struct {
    name string
}

func (p Person) Speak() {
    fmt.Println(p.name, ": 你好!")
}
Copy after login

Now we want to create an animal Type, which can "inherit" dogs and cats, and also has its own properties and methods, such as color and running speed. We can define it like this:

type Animal struct {
    Dog
    Cat
    color       string
    runSpeed    int
}

func (a Animal) Run() {
    fmt.Println(a.color, "的动物以", a.runSpeed, "km/h的速度奔跑!")
}
Copy after login

In this definition, the Animal type embeds the Dog and Cat types. This means that objects instantiated of type Animal can directly access the properties and methods of types Dog and Cat. We can also define our own properties and methods for the Animal type, such as color and runSpeed, to represent the animal's color and running speed, and define a Run method to describe the animal's running action.

Now let’s create an Animal object and see how it works:

func main() {
    d := Dog{name: "小黑"}
    c := Cat{name: "小白"}
    a := Animal{d, c, "黑白相间", 50}
    a.Bark()    // 小黑 : 汪汪汪!
    a.Mew()     // 小白 : 喵喵喵!
    a.Run()     // 黑白相间 的动物以 50 km/h的速度奔跑!
}
Copy after login

We can see that by embedding the Dog and Cat types, the Animal object can directly call the Bark and Mew methods , without using interfaces or other means. This approach allows us to achieve similar functionality without using "inheritance" in the traditional sense.

  1. Embedding custom types

We can embed a custom type into another custom type to achieve an effect similar to inheritance. Now, let's define a Person type and a Student type, and embed the Person type into the Student type:

type Person struct {
    name string
    age  int
    sex  string
}

type Student struct {
    Person
    class string
    score float64
}
Copy after login

In this definition, the Student type embeds the Person type. When instantiating a Student type object, you can use the properties and methods of Person. For example, we can instantiate a student object and set his name, age, gender, class and grades:

func main() {
    s := Student{
        Person: Person{
            name: "小明",
            age:  18,
            sex:  "男",
        },
        class: "高三一班",
        score: 92.5,
    }
    fmt.Println("姓名:", s.name)
    fmt.Println("年龄:", s.age)
    fmt.Println("性别:", s.sex)
    fmt.Println("班级:", s.class)
    fmt.Println("成绩:", s.score)
}
Copy after login

When we run this program, we can see the following output:

姓名: 小明
年龄: 18
性别: 男
班级: 高三一班
成绩: 92.5
Copy after login

We can see that the Student object can directly access the properties and methods of the Person type object, including attributes such as name, age, and sex.

  1. Nested embedding

It is also possible to nest multiple types within a type. We can embed the Animal type into another type to achieve more functions. For example, let's define a Zoo type now:

type Zoo struct {
    Animal
    name    string
    address string
}

func (z Zoo) ShowInfo() {
    fmt.Println("这是", z.name, ", 地址是", z.address)
    z.Run()
}
Copy after login

In the definition of this type, we embed the Animal type into the Zoo type. In this way, the Zoo type can directly access the properties and methods of the Animal type, including the Run method. We define another ShowInfo method to output the name and address of the zoo, and call the Run method of the Animal type to show the animals running.

Now, we create a zoo object and test its methods:

func main() {
    d := Dog{name: "小黑"}
    c := Cat{name: "小白"}
    a := Animal{d, c, "黑白相间", 50}
    z := Zoo{a, "北京动物园", "北京市海淀区清华科技园路"}
    z.ShowInfo()
}
Copy after login

When we run this program, we can see the output as follows:

这是 北京动物园 , 地址是 北京市海淀区清华科技园路
黑白相间 的动物以 50 km/h的速度奔跑!
Copy after login

We can see By nesting the Animal type into the Zoo type, we can create a type with more functions that can display zoo information and the running actions of animals.

Summary

Although there are no concepts of classes and inheritance defined by traditional object-oriented languages ​​in the Go language, the concept of embedding allows us to Achieve similar functions with more flexibility and convenience. Through the above examples, we can see that embedding makes it easy to create a type that contains subtypes and to conveniently call their methods and properties.

The above is the detailed content of How to inherit in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!