10 接口(interface)

一、接口Interface

接口是一种特殊的类型,抽象类型。

1.定义

/*
type 接口名 interface{
	方法名1(参数1, 参数2...)(返回值1, 返回值2...)
	方法名2(参数1, 参数2...)(返回值1, 返回值2...)
	...
}
*/

//定义runer接口
type runer interface {
	run()
}

//定义eater接口
type eater interface {
	eat(string)
}

2.实现

//定义dog类型
type dog struct {
	name string //动物名称
}

//定义person类型
type person struct {
	name string //姓名
}

//给dog类实现run接口
func (a *dog) run() {
	fmt.Printf("%s正在跑...\n", a.name)
}

//给dog类实现eat接口
func (a *dog) eat(food string) {
	fmt.Printf("%s正在吃%s...\n", a.name, food)
}

//给person类实现run接口
func (p *person) run() {
	fmt.Printf("%s正在跑...\n", p.name)
}

//给person类实现eat接口
func (p *person) eat(food string) {
	fmt.Printf("%s正在吃%s...\n", p.name, food)
}

3.使用

//测试runer接口
func test_runer(r runer) {
	r.run()
}

//测试eater接口
func test_eater(food string, e eater) {
	e.eat(food)
}

func main() {
	var a dog
	a.name = "哈士奇"

	var p person
	p.name = "张三"

	//test_runer可以接收dog和person两种类型
	test_runer(&a)
	test_runer(&p)

	//test_eater可以接收dog和person两种类型
	test_eater("骨头", &a)
	test_eater("披萨", &p)
}

输出:

哈士奇正在跑...
张三正在跑...
哈士奇正在吃骨头...
张三正在吃披萨...

二、接口嵌套

1.定义

type animal interface {
	runer
	eater
}

//定义runer接口
type runer interface {
	run()
}

//定义eater接口
type eater interface {
	eat(string)
}

2.使用

//测试animal接口
func test_animal(food string, a animal) {
	a.run()
	a.eat(food)
}

func main() {
	var a dog
	a.name = "哈士奇"

	var p person
	p.name = "张三"

	//animal可以接收dog和person两种类型
	test_animal("骨头", &a)
	test_animal("披萨", &p)
}

输出:

哈士奇正在跑...
哈士奇正在吃骨头...
张三正在跑...
张三正在吃披萨...

三、空接口

1.定义

interface{} //空接口

2.使用

func main() {
	var m map[int]interface{}
	m = make(map[int]interface{}, 1)
	m[1] = "哈士奇"
	m[2] = 5000
	m[3] = true
	m[4] = [...]int{0, 1, 2, 3, 4, 5, 6}

	fmt.Println(m) //map[1:哈士奇 2:5000 3:true 4:[0 1 2 3 4 5 6]]
}

3.类型断言

func assign(i interface{}) {
	fmt.Printf("type:%T\n", i)
	switch i.(type) {
	case string:
		fmt.Println("this is a string.")
	case bool:
		fmt.Println("this is a boolean.")
	case int:
		fmt.Println("this is a int.")
	case int64:
		fmt.Println("this is a int64.")
	default:
		fmt.Println("this is unknow type.")
	}
}

func main() {
	assign(10)
	assign("哈士奇")
	assign("true")
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值