接口初识

package main


import(
	"fmt"
)
//声明|定义一个接口
type Usb interface{
	//声明了两个没有实现的方法
	start()
	stop()
}
type Phone struct {}

//让phone 实现Usb接口的方法
func (p Phone) start(){
	fmt.Println("手机开始工作。。。")
}
func (p Phone) stop(){
	fmt.Println("手机停止工作。。。")
}

type Camera struct {}
//让phone 实现Usb接口的方法
func (c Camera) start(){
	fmt.Println("相机开始工作。。。")
}
func (c Camera) stop(){
	fmt.Println("相机停止工作。。。")
}

//计算机
type computer struct{}

//编写一个方法working 方法,接收一个Usb接口类型变量
//只要是实现了Usb接口(所谓实现usb接口,就是指实现了Usb接口声明所有方法)
func (c computer) Working(usb Usb){
	//通过usb接口变量来调用start和stop方法
	usb.start()
	usb.stop()
}
func main() {
	//测试
	//先创建结构体变量
	computer := computer{}
	phone := Phone{}
	camera := Camera{}

	//关键点
	computer.Working(phone)
	computer.Working(camera)
}

输出:

手机开始工作。。。
手机停止工作。。。
相机开始工作。。。
相机停止工作。。。
posted @ 2022-03-20 23:01  ty1539  阅读(26)  评论(0编辑  收藏  举报