第四天

作者: 可问春风渡江陵 | 来源:发表于2019-03-25 10:25 被阅读0次

一、面向对象编程

1、特性

  • 没有封装、继承、多态
  • 封装通过方法实现
  • 继承通过匿名字段实现
  • 多态通过接口实现

2、继承(匿名组合)

type Person struct{
    name string
    sex byte
    age int
}


type Student struct{
    Person
    id int
    addr string
}


var s1 = Student{Person{"ccc",'m',20},13,"hz"}

s2 := Student{Person{name:"ccc"},12,"hz"}

s3 := Student{Person:Person{sex:'m'}}

s1.name = "mike"
s1.Person = Person{"mike",'m',20}


  • 同名字段
    s1.Person.name = "wang"

  • 非结构体匿名变量

type Student struct{
    Person
    int
    string
}


s1 := Student{Person{name:"ccc"},666,"hz"}

s1.int //访问
  • 结构体指针类型成员变量赋值
type Student struct{
    *Person
    int
    string
}


1.
s1 := Student{&Person{"ccc",'m',20},1,"hz"}
s1.name

2.
var s2 Student
s2.Person = new(Person)
s2.name = "ccc"

3、方法

func fun1(a int)(){
    
}

func (a int){
    
}

//带有接收者的函数
func (c int) fun2(a int) long {
    return c + b
}

a := 3

result := a.func2(4)

1、面向对象。方法:给某个类型绑定一个函数

  • 接受者:就是传递的另一个参数

2、值语义和引用语义

3、方法集,

  • T能调用方法的集合(T可以调用T的方法,内部会做转换 ;T也可以调用T的方法,内部也会自动转换)

4、方法的继承

  • 结构体继承的时候,成员变量和函数会一起被继承

5、方法的重写(方法的同名方法)

  • 继承可以进行方法重写
  • 可以指定调用

6、方法值与方法表达式(函数指针的使用)

  • 方法值:保存方法的入口地址
  • 方法表达式

4、接口

//定义接口类型
type Humaner interface{
    //方法,只有声明,没有实现,由别的类型(自定义类型)实现
    sayHi()
}

只要实现了接口的方法,就可以向这个接口类型进行赋值,并调用达到多态的效果

4.1 继承

type Personer interface{
    //方法,只有声明,没有实现,由别的类型(自定义类型)实现
    sing(lrc String)
}

4.2 接口转换

  • 超集可以转换为子集,子集不能转换为超集

4.3 空接口(万能类型)

  • 不包含方法,可以保存任何类型的值
  • 使用场景:打印函数
  • interface {}

4.3 类型断言(类型查询)

4.3.1 if

if value ,ok := data.(int);ok == true

4.3.2 switch

switch value := data.(type)

相关文章

网友评论

      本文标题:第四天

      本文链接:https://www.haomeiwen.com/subject/lkxvvqtx.html