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()
*/
}
- go语言学习-接口(interface)
- Go语言接口interface
- Go语言学习笔记 --- interface
- Go语言学习笔记(四)结构体struct & 接口Interface & 反射
- go - interface 接口
- Go语言学习笔记---接口
- go语言学习-接口赋值
- Go语言学习之interface(The way to go)
- go语言 interface 初探
- Go语言interface详解
- Go语言基础:Interface
- Go语言interface详解
- Go语言interface详解
- Go语言-interface
- GO语言interface
- Go语言-interface
- go语言学习笔记-接口学习
- Go学习笔记:interface
- 牛客网 | 叠罗汉I && II
- 一天的总结(2016/01/12)
- java访问未验证证书的HTTPS
- EditText的详细使用
- HDU 1024 Max Sum Plus Plus (最大子序和)
- go语言学习-接口(interface)
- CocoaPods的安装和使用
- 分享一个链接
- [Python标准库]datetime——日期和时间值管理
- choose AC-Coupling
- Imageloder 源码阅读笔记
- 路由转发过程的IP及MAC地址变化
- Arithmetic Progression
- Codeoforces 577B Modulo Sum (鸽巢定理+dp)