使用Golang的interface接口设计原则

栏目: Go · 发布时间: 6年前

1、interface接口

interface 是 GO 语言的基础特性之一。可以理解为一种类型的规范或者约定。它跟java,C# 不太一样,不需要显示说明实现了某个接口,它没有继承或子类或“implements”关键字,只是通过约定的形式,隐式的实现interface 中的方法即可。因此,Golang 中的 interface 让编码更灵活、易扩展。

如何理解go 语言中的interface ? 只需记住以下三点即可:

注意:

a. interface 可以被任意对象实现,一个类型/对象也可以实现多个 interface

b. 方法不能重载,如eat(), eat(s string)不能同时存在

package main import "fmt" type Phone interface { call() } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } type ApplePhone struct { } func (iPhone ApplePhone) call() { fmt.Println("I am Apple Phone, I can call you!") } func main() { var phone Phone phone = new(NokiaPhone) phone.call() phone = new(ApplePhone) phone.call() }

上述中体现了interface接口的语法,在main函数中,也体现了多态的特性。

更多go语言内容请关注: http://www.fastgolang.com


以上所述就是小编给大家介绍的《使用Golang的interface接口设计原则》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Struts 2 in Action

Struts 2 in Action

Don Brown、Chad Davis、Scott Stanlick / Manning Publications / 2008.3 / $44.99

The original Struts project revolutionized Java web development and its rapid adoption resulted in the thousands of Struts-based applications deployed worldwide. Keeping pace with new ideas and trends......一起来看看 《Struts 2 in Action》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码