【Go】基礎文法之介面

來源:互聯網
上載者:User

標籤:

介面定義:

利用關鍵字interface來定義一個介面,介面是一組方法的集合。

例如:

type People interface {    Show(name string, age int) (id int, err error)      Set(name string, age int)}
介面的實現:

跟結構體的成員方法實現是一樣的。

func (object of implement func) func_name (parameters) (return type){

    ....//func body

}

例如:

package mainimport "fmt"func main() {    fmt.Println("=================Live interface===============")    var live Live    s := &Student{People{"puyangsky", 22, 007}, 0}    live = s    live.speak("I am happy")    live.eat()    fmt.Println("================Earn interface================")    var earn Earn    earn = &Worker{People{"humeiling", 22, 002}, 0}    earn.eat()    earn.work()    earn.getMoney(100)    fmt.Println("=====================End======================")}type People struct {    name string    age int32    id int32}type Student struct{    People    grade float32}type Worker struct{    People    salary float32}type Live interface {    eat()    speak(something string)}type Earn interface {    eat()    work()    getMoney(money int32)}func (s *Student) eat()  {    fmt.Printf("%s is eating...\n", s.name)}func (s *Student) speak(something string) {    fmt.Printf("%s is speaking: %s\n", s.name, something)}func (w *Worker) eat()  {    fmt.Printf("%s is eating ...\n", w.name)}func (w *Worker) work()  {    fmt.Printf("%s is working...\n", w.name)}func (w *Worker) getMoney(money int32) {    fmt.Printf("%s earned %d money..\n", w.name, money)}

結果如下:

 

介面的使用:

一個結構體必須實現了一個介面的所有方法,才能被一個介面對象接受。這一點和Java語言中的介面的要求是一樣的。

例如上例中的Live介面的對象live,只能接受實現了Live介面所有方法的Student結構體的對象,而不能接受其他結構體的對象。

一個介面可以被多個結構體實現,一個結構體可以實現多個介面的方法,是多對多的關係。

使用方法:先定義一個介面的對象,用實現了該介面所有方法的結構體的對象來初始化該介面對象,然後就可以通過該介面對象來提供者的方法。

【Go】基礎文法之介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.