咔咔博客之面向对象:多态的类型断言
在面向对象:多态这一节最后没有进行类型断言,也就是类型判断。那么在这篇文章中就简单的介绍一下html
案例
案例总结
在进行类型断言会有俩种方式微信
- 第一种则是switch
- 第二种就是if判断
switch是使用类型来判断 也就是s.(type)app
if判断是把指针跟定义的值判断url
代码
package main import ( "fmt" ) // 定义工人接口 type Worker1 interface { // 天天工做多少小时,产出何种产品 Work1(hour int) (chanpin string) // 休息 Rest1() } // 定义码农 type Coder1 struct { skill string } func (Coder *Coder1) Work1(hour int) (chanpin string) { fmt.Printf("码农一天工做%d小时\n", hour) return "BUG" } func (Coder *Coder1) Rest1() { fmt.Println("休息是什么???") } // 定义产品经理 type ProductManager1 struct { skill string } func (P *ProductManager1) Work1(hour int) (chanpin string) { fmt.Printf("产品一天工做%d小时\n", hour) return "无逻辑的需求" } func (P *ProductManager1) Rest1() { fmt.Println("产品能够使劲的休息") } // 定义boos type Boos1 struct { skill string } func (Boos *Boos1) Work1(hour int) (chanpin string) { fmt.Printf("boos一天工做%d小时\n", hour) return "梦想" } func (Boos *Boos1) Rest1() { fmt.Println("无休息") } func main() { // 建立一个工人切片保存三种职业 // 这里须要注意一个点 这个切片的名字Worker须要跟接口名一致 workers := make([]Worker1, 0) // 往切片添加的都是指针并不是值,由于在方法主语用的是指针形式 (Boos *Boos) workers = append(workers, &Coder1{ skill: "写代码"}) workers = append(workers, &ProductManager1{ skill: "提需求"}) workers = append(workers, &Boos1{ skill: "想方案"}) // 建立一个种子 //r := rand.New(rand.NewSource(time.Now().UnixNano())) // 建立一个随机数表明星期几 //weekday := r.Intn(7) // 类型断言方式一 /** 休息是什么??? 任何指针都不属于 无休息 */ for _, s := range workers { switch s.(type) { case *Coder1: s.Rest1() case *Boos1: s.Rest1() default: fmt.Println("任何指针都不属于") } } // 类型断言方式二 /** 若是是:ok为true,Coder1Ptr有值 若是不是:ok为false,Coder1Ptr为nil */ for _, s := range workers { if Coder1Ptr, ok := s.(*Coder1); ok { // 码农一天工做10小时 Coder1Ptr.Work1(10) } } }