Go interface 理解

interface 抽离了方法和具体的实现。 java

举个例子: shell

你去ATM机存款 ,你但愿的是,你存钱以后银行会存到你的帐上,而且还会计算利息。 ubuntu

可是你不用关心银行是怎么把存款记到你的帐上的,也不用关心银行是怎么计算利息的。 ide

那这跟接口interface  有个毛线关系 ? oop

能够这样理解(理解有错的话不要喷我,我也是刚学GO) : this

-->  银行提供 接口 interface 
    #code:
        type Bank interface  {
            Save() int    //进帐 
            Get() int       //取钱
            Query() int   //查询 
        }

-->  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的全部接口
--> 咱们操做ATM触发的动做
atm := ATM{client:yeelone ,money:300}

bank:=  Bank(atm)
bank.save()

GO的interface 大概就是这个样子了,不过我一开始有个疑问,GO 是怎么知道我实现了哪一个接口的? spa

拿java的语法来举个例子: code

public class Rectangle implements Shaper { //implementation here } 接口

java 会很清楚的告诉你实现了哪一个接口,那Go是怎么作到的? io

其实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[n])
         fmt.Println("Area of this shape is: ", shapesArr[n].Area())
     }
}

不一样的形状计算面积的方式是不一样的。

输出结果:

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
相关文章
相关标签/搜索