go語言學習-介面(interface)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

在Go語言出現之前,介面主要作為不同組件之間的契約存在。

 

1、侵入式介面(go語言之前的幾乎所有物件導向語言的介面定義方式):

實作類別需要明確的說明自己實現了某個介面(直接指定了介面)。如:

interface IFoo {

void Bar();

}

class Foo implements IFoo { // Java文法

// ...

}

class Foo : public IFoo { // C++文法

// ...

}

 

2、非侵入式介面:

介面定義的時候,不需要指明和某個具體累的關係;同時定義類的時候,也不需要知道和那個介面相聯絡。

優點:

(1) Go語言的標準庫,再也不需要繪製類庫的繼承樹圖,你只需要知道這個類實現了哪些方法,每個方法是啥含義就足夠了;

(2) 實作類別的時候,只需要關心自己應該提供哪些方法,不用再糾結介面需要拆得多細才合理,介面由使用方按需定義,而不用事前規劃;

(3) 不用為了實現某一個介面而引入一個包,從而能夠減少耦合。

註:go語言中,一個類要執行個體化一個介面,必須定義所有介面中聲明的函數,否則在執行個體化的時候回出錯,下面例子中會提到:

 

type tmpStruct struct {

    structName string

    structAge, structHeight int

}

 

func (f_struct *tmpStruct) tmpFunc1() {

    fmt.Println("show info in func1, name is: ", f_struct.structName)

}

 

func (f_struct *tmpStruct) tmpFunc2() {

    fmt.Println("show info in func2, age is: ", f_struct.structAge)

}

 

func (f_struct *tmpStruct) tmpFunc3() {

    fmt.Println("show info in func3, height is: ", f_struct.structHeight)

}

 

type tmpInterface interface {

    tmpFunc1()

    tmpFunc2()

    tmpFunc3()

}

 

type tmpInterface_extern interface {

    tmpFunc1()

    tmpFunc4()

}

 

func main() {

    var inter1 tmpInterface = &tmpStruct{"name_temp", 22, 180}

 

    inter1.tmpFunc1()

    inter1.tmpFunc2()

    inter1.tmpFunc3()

 

//下面的代碼回編譯失敗,因為tmpStruct並沒有實現tmpInterface_extern介面中的所有方法

/* 編譯錯誤資訊如下:

    cannot use new(tmpStruct) (type *tmpStruct) as type tmpInterface_extern in assignment:

    *tmpStruct does not implement tmpInterface_extern (missing tmpFunc4 method) */

/*

    var inter_extern tmpInterface_extern = new(tmpStruct)

    inter_extern.tmpFunc1()

    inter_extern.tmpFunc4()

*/

}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.