code explame
如下所示为一个interface的代码示例。那么要如何理解这个interface呢,官方说的是interface是一组方法签名的集合,谁实现了这个签名集合的所有方法,谁就实现了这个interface。代码&用例图如下所示
package main
import "fmt"
type People interface {
name(name string)
age(age int)
}
type Student struct {
score uint
}
type Teacher struct {
}
func (s *Student) name(nm string) {
fmt.Println("Student name is %s ", nm)
}
func (s *Student) age(age int) {
fmt.Println("Student age is ", age)
}
func (t *Teacher) name(nm string) {
fmt.Println("Teacher name is ", nm)
}
func (t *Teacher) age(age int) {
fmt.Println("Teacher age is ", age)
}
// 定义interface变量
var conn People
func GetStudentConn() People {
conn = &Student{score: 100}
return conn
}
func GetTeacherConn() People {
conn = &Teacher{}
return conn
}
func main() {
stuConn := GetStudentConn()
stuConn.age(100)
teaConn := GetTeacherConn()
teaConn.name("tea")
}
复制代码
在本人看来,go的interface有点像cpp中的抽象类这种概念,cpp的抽象类是指抽象类只定义纯虚函数的签名,由其子类具体实现这些函数的签名,只有在main函数中具体调用的时候才知道具体是哪个子类发生的行为(也有人说go的interface像cpp的多态,本人对比了下,cpp的多态是指基类指针指向子类对象,从而使得虚函数指针指向子类对象虚表发生调用的行为,个人认为不像,欢迎大家讨论)
class Shape
{
public:
// 提供接口框架的纯虚函数
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// 输出对象的面积
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
复制代码
有疑问加站长微信联系(非本文作者)