原文链接 http://www.limerence2017.com/2019/09/12/golang13/#more

接口简介

golang 中接口是常用的数据结构,接口可以实现like的功能。什么叫like呢?
比如麻雀会飞,老鹰会飞,他们都是鸟,鸟有翅膀可以飞。飞机也可以飞,
飞机就是像鸟一样,like bird, 所以我们可以说飞机,气球,苍蝇都像鸟一样可以飞翔。
但他们不是鸟,那么对比继承的关系,老鹰继承自鸟类,它也会飞,但他是鸟。
先看一个接口定义

1
2
3
type Bird interface {
Fly() string
}

定义了一个Bird类型的interface, 内部生命了一个Fly方法,参数为空,返回值为string。
接口声明方法和struct不同,接口的方法写在interface中,并且不能包含func和具体实现。
另外interface内部不能声明成员变量。
下面去实现蝴蝶类和飞机类,实现like-bird的功能。像鸟一样飞。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type Plane struct {
name string
} func (p *Plane) Fly() string {
fmt.Println(p.name, " can fly like a bird")
return p.name
} type Butterfly struct {
name string
} func (bf *Butterfly) Fly() string {
fmt.Println(bf.name, " can fly like a bird")
return bf.name
}

实现了Plane和Butterfly类,并且实现了Fly方法。那么飞机和蝴蝶就可以像鸟一样飞了。
我们在主函数中调用

1
2
3
4
5
   pl := &Plane{name: "plane"}
pl.Fly() bf := &Butterfly{name: "butterfly"}
bf.Fly()

输出如下

1
2
plane  can fly like a bird
butterfly can fly like a bird

有人会问,单独实现Plane和Butterfly不就好了,为什么要和Bird扯上关系呢?
因为接口作为函数形参,可以接受不同的实参类型,只要这些实参实现了接口的方法,
都可以达到动态调用不同实参的方法。

1
2
3
func FlyLikeBird(bird Bird) {
bird.Fly()
}

下面我们在main函数中调用上面这个函数,传入不同的实参

1
2
   FlyLikeBird(pl)
FlyLikeBird(bf)

输出如下

1
2
plane  can fly like a bird
butterfly can fly like a bird

这样就是实现了动态调用。有点类似于C++的多态,golang又不是通过继承达到这个效果的,
只要结构体实现了接口的方法就可以转化为接口类型。
golang这种实现机制突破了Java,C++等传统静态语言显示继承的弊端。

接口类型转换和判断

struct类型如果实现了接口方法,可以赋值给对应的接口类型,接口类型同样可以转化为struct类型。
我们再写一个函数,通过该函数内部将bird接口转化为不同的类型,从而打印具体的传入类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func GetFlyType(bird Bird) {
_, ok := bird.(*Butterfly)
if ok {
fmt.Println("type is *butterfly")
return
} _, ok = bird.(*Plane)
if ok {
fmt.Println("type is *Plane")
return
} fmt.Println("unknown type")
}

main函数调用

1
2
3
4
5
6
func main() {
pl := &Plane{name: "plane"}
bf := &Butterfly{name: "butterfly"}
GetFlyType(pl)
GetFlyType(bf)
}

输出如下

1
2
type is *Plane
type is *butterfly

看得出来接口也是可以转化为struct的。
结构体变量, bool类型:=接口类型.(结构体类型)
bool类型为false说明不能转化,true则能转化。

万能接口interface{}

golang 提供了万能接口, 类型为interface{}, 任何具体的结构体类型都能转化为该类型。我们将之前判断类型的例子
稍作修改。定义Human类和Human的Walk方法,然后实现另一个判断函数,参数为interface{}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type Human struct {
} func (*Human) Walk() { } func GetFlyType2(inter interface{}) {
_, ok := inter.(*Butterfly)
if ok {
fmt.Println("type is *butterfly")
return
} _, ok = inter.(*Plane)
if ok {
fmt.Println("type is *Plane")
return
}
_, ok = inter.(*Human)
if ok {
fmt.Println("type is *Human")
return
}
fmt.Println("unknown type")
}

在main函数中调用,我们看看结果

1
2
3
4
5
6
7
8
func main() {
pl := &Plane{name: "plane"}
bf := &Butterfly{name: "butterfly"}
hu := &Human{}
GetFlyType2(pl)
GetFlyType2(bf)
GetFlyType2(hu)
}

看到输出

1
2
3
type is *Plane
type is *butterfly
type is *Human

.(type)判断具体类型

接口还提供了一个功能,通过.(type)返回具体类型,但是.(type)只能用在switch中。
我们实现另一个版本的类型判断

1
2
3
4
5
6
7
8
9
10
11
12
func GetFlyType3(inter interface{}) {
switch inter.(type) {
case *Butterfly:
fmt.Println("type is *Butterfly")
case *Plane:
fmt.Println("type is *Plane")
case *Human:
fmt.Println("type is *Human")
default:
fmt.Println("unknown type ")
}
}

main函数中调用这个函数

1
2
3
   GetFlyType3(pl)
GetFlyType3(bf)
GetFlyType3(hu)

输出结果如下

1
2
3
type is *Plane
type is *Butterfly
type is *Human

所以.(type)也实现了类型转换

这样接口基础都介绍完毕了,下一篇介绍接口内部实现和剖析。
感谢关注我的公众号

golang(08)接口介绍的更多相关文章

  1. 【玩转单片机系列001】 08接口双色LED显示屏驱动方式探索

    前些日子,从淘宝上购得一块08接口的双色LED显示屏(打算做个音乐频谱显示器),捣鼓了好几天,终于搞清楚了其控制原理,在这里做个总结,算是备忘吧. 1.LED显示屏的扫描方式 LED显示屏的扫描方式有 ...

  2. Hive 接口介绍(Web UI/JDBC)

    Hive 接口介绍(Web UI/JDBC) 实验简介 本次实验学习 Hive 的两种接口:Web UI 以及 JDBC. 一.实验环境说明 1. 环境登录 无需密码自动登录,系统用户名shiyanl ...

  3. SSH动态查询封装接口介绍

    SSH动态查询封装接口介绍 1.查询记录总条数 public int count(Class c,Object[][] eq,Object[][] like,String[] group,String ...

  4. 【百度地图API】如何在地图上添加标注?——另有:坐标拾取工具+打车费用接口介绍

    原文:[百度地图API]如何在地图上添加标注?--另有:坐标拾取工具+打车费用接口介绍 摘要: 在这篇文章中,你将学会,如何利用百度地图API进行标注.如何使用API新增的打车费用接口. ------ ...

  5. 如何删除要素类 IFeatureWorkspace 接口介绍(1)

    如何删除要素类 要想删除一个要素类,那么必须先得到这个,在得到这个要素类的时候,我们要学习一个新的接口IFeatureWorkspace. IFeatureWorkspace  接口介绍 这个接口主要 ...

  6. Redis --> Redis的接口介绍及使用

    Redis的接口介绍及使用 Redis是一个远程内存数据库,它不仅性能强劲,而且还具有复制特性以及为解决问题而生的独一无二的数据模型.Redis提供了5种不同类型的数据结构,各式各样的问题都可以很自然 ...

  7. iic接口介绍

    最近遇到一个BUG,跟IIC通信有关,所以借这个机会总结一下IIC总线协议 1.引脚接口介绍 1.A0,A1,A2为24LC64的片选信号,IIC总线最多可以挂载8个IIC接口器件,通过对A0,A1, ...

  8. Spring之InstantiationAwareBeanPostProcessor接口介绍

      InstantiationAwareBeanPostProcessor接口是BeanPostProcessor的子接口,通过接口字面意思翻译该接口的作用是感知Bean实例话的处理器.实际上该接口的 ...

  9. I2S接口介绍

    I2S接口介绍一.I2S协议介绍 I2S协议作为音频数据传输协议,由Philips制定.该协议由三条数据线组成:1.SCLK:串行时钟,频率= 2 * 采样频率 * 采样位数.2.WS:字段(声道)选 ...

随机推荐

  1. 数据库——Oracle(3)

    1 排序:对查询返回的结果,根据某一个列或者某几个列的列值大小进行升序或者降序排列. 1)根据某一个列的列值大小进行升序或者降序排列 格式: select 列名/* from 表名 order by ...

  2. 浅谈浏览器存储(cookie、localStorage、sessionStorage)

    今天我们从前端的角度了解一下浏览器存储,我们常见且常用的存储方式主要由两种:cookie.webStorage(localStorage和sessionStorage).下面我们来一一认识它们. Co ...

  3. spring cache会默认使用redis作为缓存吗?

    web项目中,只需要配置 redis 的IP,端口,用户名和密码就可以使用redis作为缓存了,不需要在在java 代码中配置redisConfig,redisConfig只是作为缓存配置的辅助,比如 ...

  4. Atcoder CODE FESTIVAL 2016 Final G - Zigzag MST[最小生成树]

    题意:$n$个点,$q$次建边,每次建边选定$x,y$,权值$c$,然后接着$(y,x+1,c+1),(x+1,y+1,c+2),(y+1,x+2,c+3),(x+2,y+2,c+4)\dots$(画 ...

  5. Web前端开发——概述

    前端技术构成: 结构:html,从语义的角度,描述页面结构 样式:css,从审美的角度,美化界面样式 行为:JavaScript,从交互的角度,提升用户体验 前端技术标准: 前端技术的标准就是由W3C ...

  6. SQL 日期转换

    ), ): :57AMSELECT ), ): ), ): ), ): ), ): ), ): ), ): 06), ): ,06), ): ::46), ): :::827AMSELECT ), ) ...

  7. 适合没有ui的项目的样式

    官网: https://www.tailwindcss.cn/

  8. 线性素数筛(欧拉筛)(超级好的MuBan)

    Problem:找出小于等于n的所有素数的个数. #include <bits/stdc++.h> using namespace std; const int maxn = 1e6; i ...

  9. Lock和synchronized的区别

    总结来说,Lock和synchronized有以下几点不同: 1)Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现: 2)synchroni ...

  10. apt 和 apt-get的区别

    apt 和 apt-get的区别 - liudsl的博客 - CSDN博客  https://blog.csdn.net/liudsl/article/details/79200134 Linux软件 ...