一,interface 介绍

如果说 goroutine 和 channel 是 go 语言并发的两大基石,那 interface 就是 go 语言类型抽象的关键。在实际项目中,几乎所有的数据结构最底层都是接口类型。说起 C++ 语言,我们立即能想到是三个名词:封装、继承、多态。go 语言虽然没有严格意义上的对象,但通过 interface,可以说是实现了多态性。(由以组合结构体实现了封装、继承的特性)

go 语言中支持将 method、struct、struct 中成员定义为 interface 类型,使用 struct 举一个简单的栗子

 package main

 type animal interface {
Move()
} type bird struct{} func (self *bird) Move() {
println("bird move")
} type beast struct{} func (self *beast) Move() {
println("beast move")
} func animalMove(v animal) {
v.Move()
} func main() {
var a *bird
var b *beast
animalMove(a) // bird move
animalMove(b) // beast move
}

使用 go 语言的 interface 特性,就能实现多态性,进行泛型编程。

二,interface 原理

如果没有充分了解 interface 的本质,就直接使用,那最终肯定会踩到很深的坑,要用就先要了解,先来看看 interface 源码

 type eface struct {
_type *_type
data unsafe.Pointer
} type _type struct {
size uintptr // type size
ptrdata uintptr // size of memory prefix holding all pointers
hash uint32 // hash of type; avoids computation in hash tables
tflag tflag // extra type information flags
align uint8 // alignment of variable with this type
fieldalign uint8 // alignment of struct field with this type
kind uint8 // enumeration for C
alg *typeAlg // algorithm table
gcdata *byte // garbage collection data
str nameOff // string form
ptrToThis typeOff // type for pointer to this type, may be zero
}

可以看到 interface 变量之所以可以接收任何类型变量,是因为其本质是一个对象,并记录其类型和数据块的指针。(其实 interface 的源码还包含函数结构和内存分布,由于不是本文重点,有兴趣的同学可以自行了解)

三,interface 判空的坑

对于一个空对象,我们往往通过 if v == nil 的条件语句判断其是否为空,但在代码中充斥着 interface 类型的情况下,很多时候判空都并不是我们想要的结果(其实了解或聪明的同学从上述 interface 的本质是对象已经知道我想要说的是什么)

 package main

 type animal interface {
Move()
} type bird struct{} func (self *bird) Move() {
println("bird move")
} type beast struct{} func (self *beast) Move() {
println("beast move")
} func animalMove(v animal) {
if v == nil {
println("nil animal")
}
v.Move()
} func main() {
var a *bird // nil
var b *beast // nil
animalMove(a) // bird move
animalMove(b) // beast move
}

还是刚才的栗子,其实在 go 语言中 var a *bird 这种写法,a 只是声明了其类型,但并没有申请一块空间,所以这时候 a 本质还是指向空指针,但我们在 aminalMove 函数进行判空是失败的,并且下面的 v.Move() 的调用也是成功的,本质的原因就是因为 interface 是一个对象,在进行函数调用的时候,就会将 bird 类型的空指针进行隐式转换,转换成实例的 interface animal 对象,所以这时候 v 其实并不是空,而是其 data 变量指向了空。这时候看着执行都正常,那什么情况下坑才会绊倒我们呢?只需要加一段代码

 package main

 type animal interface {
Move()
} type bird struct {
name string
} func (self *bird) Move() {
println("bird move %s", self.name) // panic
} type beast struct {
name string
} func (self *beast) Move() {
println("beast move %s", self.name) // panic
} func animalMove(v animal) {
if v == nil {
println("nil animal")
}
v.Move()
} func main() {
var a *bird // nil
var b *beast // nil
animalMove(a) // panic
animalMove(b) // panic
}

在代码中,我们给派生类添加 name 变量,并在函数的实现中进行调用,就会发生 panic,这时候的 self 其实是 nil 指针。所以这里坑就出来了。有些人觉得这类错误谨慎一些还是可以避免的,那是因为我们是正向思维去代入接口,但如果反向编程就容易造成很难发现的 bug

 package main

 type animal interface {
Move()
} type bird struct {
name string
} func (self *bird) Move() {
println("bird move %s", self.name)
} type beast struct {
name string
} func (self *beast) Move() {
println("beast move %s", self.name)
} func animalMove(v animal) {
if v == nil {
println("nil animal")
}
v.Move()
} func getBirdAnimal(name string) *bird {
if name != "" {
return &bird{name: name}
}
return nil
} func main() {
var a animal
var b animal
a = getBirdAnimal("big bird")
b = getBirdAnimal("") // return interface{data:nil}
animalMove(a) // bird move big bird
animalMove(b) // panic
}

这里我们看到通过函数返回实例类型指针,当返回 nil 时,因为接收的变量为接口类型,所以进行了隐性转换再次导致了 panic(这类反向转换很难发现)。

那我们如何处理上述这类问题呢。我这边整理了三个点

1,充分了解 interface 原理,使用过程中需要谨慎小心

2,谨慎使用泛型编程,接收变量使用接口类型,也需要保证接口返回为接口类型,而不应该是实例类型

3,判空是使用反射 typeOf 和 valueOf 转换成实例对象后再进行判空

最新文章

  1. 启动第一个 KVM 虚机 - 每天5分钟玩转 OpenStack(4)
  2. input标签内容改变的触发事件
  3. python Gunicorn
  4. uva1588kickdown
  5. [Leetcode][JAVA] Binary Tree Maximum Path Sum
  6. 关于JavaScript的思考
  7. Newtonsoft.Json.dll使用
  8. windows中copy命令详解
  9. Win10中virtualbox新建虚拟机不能设置64位系统解决
  10. sublime 学习笔记
  11. [jzoj]2538.【NOIP2009TG】Hankson 的趣味题
  12. textarea 中的换行符
  13. RPC概念及分类【转载】
  14. js动态修改Easyui元素不生效,EasyUI动态渲染解析解决方案
  15. 002之MFCSocket异步编程
  16. [转帖]linux 内存管理——内核的shmall 和shmmax 参数
  17. qrcode模块简单使用
  18. Installation Guide Ubuntu 16.04
  19. BZOJ 3098 Hash Killer II
  20. 虚拟机的安装以及Linux的学习

热门文章

  1. wampserver apache 500 Internal Server Error解决办法
  2. 【django】另一种思路代替nginx 的rewrite
  3. VSCode 常用快捷键和常用插件及通用设置
  4. vue 自定义指令的魅力
  5. C# 之 .net core -- EF code first连接Mysql数据库
  6. 用vs2013开启一个C拖控件的项目
  7. React组件式编程Demo-用户的增删改查
  8. parseInt parseFloat isNaN Number 区别和具体的转换规则及用法
  9. Hibernate 5 升级后 getProperties 错误
  10. HDU6223 Infinite Fraction Path bfs+剪枝