您的位置:首页 > 编程语言 > Go语言

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

  • 点赞
  • 收藏
  • 分享
  • 文章举报
chizhi6641 发布了0 篇原创文章 · 获赞 0 · 访问量 66 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: