go语言基础 空接口

空接口:

一个接口中没有任何的方法。
    任意的对象都可以是该接口的实现类。

空接口类型的数组:

    那么该数组中就可以存储任意类型的数据。

空接口作为参数:

可以传入任意类型的数据。

package main

import "fmt"

//定义一个接口:
// 一个或多个方法的集合,叫接口,如果一个方法都没有,叫空接口
//实现类:对于空接口,
type Animal3 interface {
   eat()
}
//空接口
type Animal4 interface {
} 
type Dog3 struct {
   name string
}
type Cat3 struct {
   name string
}

type Rabbit struct {
   name string
} 

func (d Dog3) eat()  {
   fmt.Println("小狗,吃东西。。")
}
func (c Cat3) eat()  {
   fmt.Println("小猫,吃东西。。")
}

func test(a Animal3)  { // 接收dog3,cat3
   
}
// 空接口作为参数:代表可以接收任意类型
func test2(a Animal4)  {// dog3,cat3,rabbit
   fmt.Println(a)
}

func main()  {
   // Dog,Cat,是Animal的实现类,因为都实现类eat()
   
   d1 := Dog3{"啸天"}
   d2 := Dog3{"二黄"}
   c1:= Cat3{"咪咪"}
   c2:=Cat3{"豆豆"}
   
   as :=[4]Animal3{d1,d2,c1,c2}
   fmt.Println(as)

   test2(d1)
   test2(c1)
   test2(Rabbit{"玉兔"})
   test2(100)

   //面向对象:面向接口编程--->面向实现类编程
   // 对象.方法()

   as2 := [4]Animal4{}//如果定义空接口的数组类型,那么实际上可以存入任意类型的数据。
   as2[0] = d1
   as2[1] = c1
   as2[3] = "memeda"

   
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值