5 面向对象

1 类型系统

1.1给类型添加方法

// 为类型添加方法
type Integer int  // 定义一个新类型Integer, 它与int类型相同

func (a Integer) Less(b Integer) bool {    // 给Integer类型添加新方法 less, less 方法输入一个整数,返回布尔值
    return a < b  // 当前整数a调用less方法要传入一个整数b, 如果a<b,返回true
}

如果我们想在方法中修改对象,这种时候必须就要用到指针

func (a *Integer) Add (b Integer) {
    *a += b
}

func main()  {
    a := Integer(10)
    a.Add(5)
    fmt.Println("a is : ", a)
}

 1.2 值语义和引用语义

b = a
b.Modyfy()
// 如果a的值收到影响则a为引用类型,否则为值类型

值类型的数据:

  • 基本数据类型
  • 符合类型: 数组, 结构体, 指针
// 数组想表达引用
var a = [3]int{1,2,3}
var b = &a
b[1]++
fmt.Println(a, *b)

类似引用类型的数据:

  1. 数组切片 : 指向数组的一个区间
  2. map : 键值对
  3. channel : 执行体间的通信设施
  4. 接口 : 对一组满足某个契约的类型的抽象

1.3 结构体

定义矩阵类型

type Rect struct {。      // 定义矩形类型
    x, y float64
    width, height float64
}

func (r *Rect) Area() float64{    //定义成员方法计算矩形面积
    return r.width * r.height
}

2. 初始化

初始化Rect类型的实例

rect1 := new(Rect)
rect2 := &Rect{}
rect3 := &Rect{0, 0, 100, 200}
rect4 := {width:100, height:200}

3 匿名组合

type Base struct {   // 定义Base类
    Name string
}

func (base *Base) Par() {   // Base类实现Par方法和Run方法
    fmt.Println("par in Base")
}

func (base *Base) Run() {    
    fmt.Println("run in base")
}

type Foo struct {      // Foo类继承Base类
    Base
}

func (foo *Foo) Run() {    // Foo类重写Run方法,先执行Base的Run方法在执行自己的代码
    foo.Base.Run()
    fmt.Println("run in foo")
}

func main()  {
    foo := new(Foo)  // 实例化一个foo对象,该对象有继承自父类的Par方法和自己的Run方法
    foo.Par()
    foo.Run()
}

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

                                                                                                                                                                                                                                   

猜你喜欢

转载自www.cnblogs.com/zhangjian0092/p/12358209.html