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
相關文章
相關標籤/搜索