继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【备战春招】第5天 Go语言语法进阶指南-接口

慕仙4468190
关注TA
已关注
手记 7
粉丝 0
获赞 0

课程章节:接口

课程讲师:Gavin

课程内容:

  1. 概念与实现
  2. 多态
package interface_demo

import "fmt"

// interface for behavior
type Behavior interface {
    Run() string
    Eat() string
}

struct_demo 隐式实现,对 interface 的实现

package struct_demo

import "fmt"

// 定义cat结构体
type Cat struct {
    Animal
    ID int
    Name string
    Age int
}
package main

import "fmt"

func main() {
    // 测试接口定义变量 匿名创建方式
    dog := new(struct_demo.Dog)
    cat := new(struct_demo.Cat)
    action(dog)
    action(cat)
}

// 测试接口定义变量
func action(b interface_demo.Behavior) string {
    b.Run()
    b.Eat()
    return ""
}


func (d *Dog) Eat() string {
    fmt.Println("hello! hello!")
    return "hello! hello!"
}

func (d *Dog) Run() string {
    fmt.Println("ID : ", d.ID, "Dog is running")
    return "Dog is running"
}

func (d *Cat) Eat() string {
    fmt.Println("Cat->hello! hello!")
    return "Cat->hello! hello!"
}

func (d *Cat) Run() string {
    fmt.Println("ID : ", d.ID, "Cat is running")
    return "Cat is running"
}

课程收获:

图片描述

  1. 接口:公共方法组合起来以封装特定功能的一个集合(抽象、封装、多态)
  2. 多态:接口的多种不同实现方式
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP