Golang语言面向对象编程说明
- 1.Golang也支持面向对象编程(oop),但是和传统的面向对象编程有区别,并不是纯粹的面向对象于洋。所以我们说Golang支持面向对象编程特性是比较准确的
- 2.Golang没有类(class),Go语言的结构体(struct)和其他编程语言的类有同等的地位,可以理解为Golang是基于struct来事项oop特性的
- 3.Golang面向对象编程非常简洁,去掉了传统的oop语言的继承,方法重载,构造函数和析构函数,隐藏的this指针等等
- 4.Golang任然有面向对象编程的继承,封装和多态的特性,知识实现的方式和其他oop语言不一样,比如继承:Golang没有extends关键字,继承是通过匿名字段来实现
- 5.Golang面向对象(oop)很优雅,oop本身就是语言类型系统(type system)的一部分,通过接口(Interface)关联,耦合性低,也非常灵活,也就是说在Golang中面向接口编程是非常重要的特性
案例
package main
import (
"fmt"
)
type Cat struct {
Name string
Age int
Color string
}
func main() {
var cat1 Cat
cat1.Name = "小白"
cat1.Age = 5
cat1.Color = "black"
fmt.Println("cat1=", cat1)
fmt.Println("猫猫的信息如下:")
fmt.Println("name=", cat1.Name)
fmt.Println("age=", cat1.Age)
fmt.Println("color=",cat1.Color)
}