Hello everyone, today I will sort out the object-oriented content of the Go language and share it with you. Please advise, thank you.
Encapsulation, inheritance, and polymorphism are the three basic characteristics of object-oriented. This article mainly introduces how the Go language implements these characteristics.
The two key types of object-oriented implementation in Golang are struct
and interface
. The previous articles on the basic grammar of Golang foundation (2) and the basic grammar of Golang foundation (3) have been detailed in the article Usage and cases are introduced.
Contents of this chapter
- package
- inherit
- polymorphism
A few notes
- Go supports object orientation (OOP) and is not a pure object-oriented language;
- Go has no concept of classes, and structs are equivalent to classes in other programming languages;
- Go object-oriented programming is very simple, and it is associated through interfaces, which has low coupling and is very flexible;
In this section, I will simplify these three-layer concepts into easy-to-understand words to show you. I believe that after a few minutes, everyone will have a deep impression of object-oriented, which will be helpful for future development.
package
Encapsulation is to encapsulate the abstracted fields and operation methods together, the data is protected inside, and the fields can only be operated through the operation methods.
package main
import "fmt"
type Person struct { // 抽象出来的字段
name string
}
func (person *Person) setName(name string) { // 封装方法
person.name = name
}
func (person *Person) GetInfo() { // 封装方法
fmt.Println(person.name)
}
func main() {
p := Person{"帽儿山的枪手"}
p.setName("新名字")
p.GetInfo() // 输出 新名字
}
inherit
Inheritance, as the name suggests, can solve code reuse. In Go, you just need to nest an anonymous struct inside a struct.
Go has no explicit inheritance, instead it implements inheritance through composition.
package main
import "fmt"
type Person struct { // 抽象出的字段
name string
}
func (p *Person) getName() { // 封装方法
fmt.Println(p.name)
}
type Inherit struct { // 继承
Person
}
func main() {
i := Inherit{Person{"帽儿山的枪手"}}
i.getName() // 输出 帽儿山的枪手
}
polymorphism
Extracting their common methods to define an abstract interface is polymorphism.
package main
import "fmt"
type Birds interface { // 将共同的方法提炼出来
fly()
}
type Dove struct {
}
type Eagle struct {
}
func (d *Dove) fly() { // 封装方法
fmt.Println("鸽子在飞")
}
func (e *Eagle) fly() { // 封装方法
fmt.Println("鹰在飞")
}
func main() {
var b Birds // 多态的抽象接口
dove := Dove{}
eagle := Eagle{}
b = &dove
b.fly() // 鸽子在飞
b = &eagle
b.fly() // 鹰在飞
}
Technical articles are continuously updated, please pay more attention~~
Search WeChat public account【The Gunslinger of Maoer Mountain】, follow me
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。