Home Backend Development Golang How to inherit in golang

How to inherit in golang

May 22, 2023 pm 03:25 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Getting Started with Go: A Beginner's Guide Getting Started with Go: A Beginner's Guide Apr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles