go语言学习-接口(interface)

来源:互联网 发布:精英主义知乎 编辑:程序博客网 时间:2024/05/01 06:59

在Go语言出现之前,接口主要作为不同组件之间的契约存在。

 

1、侵入式接口(go语言之前的几乎所有面向对象语言的接口定义方式):

实现类需要明确的说明自己实现了某个接口(直接指定了接口)。如:

interface IFoo {

void Bar();

}

class Foo implements IFoo { // Java文法

// ...

}

class Foo : public IFoo { // C++文法

// ...

}

 

2、非侵入式接口:

接口定义的时候,不需要指明和某个具体累的关系;同时定义类的时候,也不需要知道和那个接口相联系。

优点:

(1) Go语言的标准库,再也不需要绘制类库的继承树图,你只需要知道这个类实现了哪些方法,每个方法是啥含义就足够了;

(2) 实现类的时候,只需要关心自己应该提供哪些方法,不用再纠结接口需要拆得多细才合理,接口由使用方按需定义,而不用事前规划;

(3) 不用为了实现某一个接口而引入一个包,从而能够减少耦合。

注:go语言中,一个类要实例化一个接口,必须定义所有接口中声明的函数,否则在实例化的时候回出错,下面例子中会提到

 

type tmpStruct struct {

    structName string

    structAge, structHeight int

}

 

func (f_struct *tmpStruct) tmpFunc1() {

    fmt.Println("show info in func1, name is: ", f_struct.structName)

}

 

func (f_struct *tmpStruct) tmpFunc2() {

    fmt.Println("show info in func2, age is: ", f_struct.structAge)

}

 

func (f_struct *tmpStruct) tmpFunc3() {

    fmt.Println("show info in func3, height is: ", f_struct.structHeight)

}

 

type tmpInterface interface {

    tmpFunc1()

    tmpFunc2()

    tmpFunc3()

}

 

type tmpInterface_extern interface {

    tmpFunc1()

    tmpFunc4()

}

 

func main() {

    var inter1 tmpInterface = &tmpStruct{"name_temp", 22, 180}

 

    inter1.tmpFunc1()

    inter1.tmpFunc2()

    inter1.tmpFunc3()

 

//下面的代码回编译失败,因为tmpStruct并没有实现tmpInterface_extern接口中的所有方法

/* 编译错误信息如下:

    cannot use new(tmpStruct) (type *tmpStruct) as type tmpInterface_extern in assignment:

    *tmpStruct does not implement tmpInterface_extern (missing tmpFunc4 method) */

/*

    var inter_extern tmpInterface_extern = new(tmpStruct)

    inter_extern.tmpFunc1()

    inter_extern.tmpFunc4()

*/

}

 

 

 

0 0
原创粉丝点击