Go interface 理解
2020-03-08 13:19
751 查看
interface 抽离了方法和具体的实现。
举个例子:
你去ATM机存款 ,你希望的是,你存钱之后银行会存到你的账上,并且还会计算利息。
但是你不用关心银行是怎么把存款记到你的账上的,也不用关心银行是怎么计算利息的。
那这跟接口interface 有个毛线关系 ?
可以这样理解(理解有错的话不要喷我,我也是刚学GO) :
--> 银行提供 接口 interface
#code:
type Bank interface {
Save() int //进账
Get() int //取钱
Query() int //查询
}
[/code]
--> ATM实现接口方法
定义ATM 结构,ATM需要的是客户的信息,以及金钱数目
type ATM struct {
client String
money int
}
//存钱
func (a ATM) Save() int {
//save money for the client
//open the bank db
//save money
client = a.client
money = a.money
}
//取钱
func (a ATM) Get() int {
// do what you want
}
//查询
func (a ATM) Query() int {
// do what you want
}
实现了Bank的所有接口
[/code]
--> 我们操作ATM触发的动作
atm := ATM{client:yeelone ,money:300}
bank:= Bank(atm)
bank.save()
[/code]
GO的interface 大概就是这个样子了,不过我一开始有个疑问,GO 是怎么知道我实现了哪个接口的?
拿java的语法来举个例子:
public class Rectangle implements Shaper { //implementation here }
java 会很清楚的告诉你实现了哪个接口,那Go是怎么做到的?
其实Go是自动判断的,只要你实现了某个接口的所有方法 ,Go就认为你实现了某个接口。
再看下面的例子(非原创哈,网上很多都是用这个例子):
package main
import "fmt"
type Shaper interface {
Area() int
}
type Rectangle struct {
length, width int
}
func (r Rectangle) Area() int {
return r.length * r.width
}
type Square struct {
side int
}
func (sq Square) Area() int {
return sq.side * sq.side
}
func main() {
r := Rectangle{length:5, width:3}
q := Square{side:5}
shapesArr := [...]Shaper{r, q}
fmt.Println("Looping through shapes for area ...")
for n, _ := range shapesArr {
fmt.Println("Shape details: ", shapesArr
)
fmt.Println("Area of this shape is: ", shapesArr
.Area())
}
}
[/code]
不同的形状计算面积的方式是不同的。
输出结果:
ubuntu@yee:/tmp$ go run rectangle.go Shape details: {5 3} Area of this shape is: 15 Shape details: {5} Area of this shape is: 25
转载于:https://my.oschina.net/jbryan/blog/133950
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 理解 go interface 的 5 个关键点
- Go interface 理解
- 理解矩阵乘法
- java--依赖、关联、聚合和组合之间区别的理解
- java 堆和栈一般理解
- 曾经的足迹——对Linux CAN驱动的理解(1)
- 深入理解js闭包
- 对于重定位我该如何理解??
- 深入理解js面向对象中的prototype
- 深入理解JavaScript系列(18):面向对象编程之ECMAScript实现(推荐)
- 对面向对象设计的理解——Java接口和Java抽象类
- 如何理解装配件、元数据、PE文件和持久化
- 移动端rem使用及理解
- Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
- 【SSH】——框架理解篇
- python直方图均衡化直观理解
- 对象多态性的理解
- 一分钟理解乐观锁和悲观锁,附深入理解乐观锁与悲观锁
- 深入理解Spring系列之四:BeanDefinition装载前奏曲
- [转载]对_stdcall的理解,和其他几种调用规则