Go不是一种典型的OO语言,它在语法上不支持类和继承的概念。
没有继承是否就无法拥有多态行为了呢?答案是否定的,Go语言引入了一种新类型—Interface,它在效果上实现了类似于C++的“多态”概念,虽然与C++的多态在语法上并非完全对等,但至少在最终实现的效果上,它有多态的影子。
那么,Go的Interface类型到底是什么呢?怎么使用呢?这正是本篇笔记试图说明的问题。
在说明Interface类型前,不得不先用Go的method(s)概念来热身,因为Go语言的interface与method(s)这两个语法有非常紧密的联系。
虽然Go语言没有类的概念,但它支持的数据类型可以定义对应的method(s)。本质上说,所谓的method(s)其实就是函数,只不过与普通函数相比,这类函数是作用在某个数据类型上的,所以在函数签名中,会有个receiver来表明当前定义的函数会作用在该receiver上。
关于methods的精确语法规范,可以参考language specification或Effective Go中的说明,这里略过。
注意:Go语言支持的除Interface类型外的任何其它数据类型都可以定义其method(而并非只有struct才支持method),只不过实际项目中,method(s)多定义在struct上而已。
在struct类型上定义method(s)的语法特性与C++中的struct支持的语法非常类似(c++中的struct定义了数据,此外也支持定义数据的操作方法),从这一点来看,我们可以把Go中的struct看作是不支持继承行为的轻量级的“类”。
2. What is Interface type in Go ?
GoLang官网language specification文档对interface type的概念说明如下:
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uni