(轉自:https://blog.csdn.net/a595364628/article/details/54598227)
一、interface
interface類型定義了一組方法,如果某個對象實現了某個介面的所有
方法,則此對象就實現了此介面。詳細的文法參考下面這個例子
type Human struct { name string age int phone string}type Student struct { Human //匿名欄位Human school string loan float32}type Employee struct { Human //匿名欄位Human company string money float32}//Human對象實現Sayhi方法func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)}// Human對象實現Sing方法func (h *Human) Sing(lyrics string) { fmt.Println("La la, la la la, la la la la la...", lyrics)}//Human對象實現Guzzle方法func (h *Human) Guzzle(beerStein string) { fmt.Println("Guzzle Guzzle Guzzle...", beerStein)}// Employee重載Human的Sayhi方法func (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone) //此句可以分成多行}//Student實現BorrowMoney方法func (s *Student) BorrowMoney(amount float32) { s.loan += amount // (again and again and...)}//Employee實現SpendSalary方法func (e *Employee) SpendSalary(amount float32) { e.money -= amount // More vodka please!!! Get me through the day!}// 定義interfacetype Men interface { SayHi() Sing(lyrics string) Guzzle(beerStein string)}type YoungChap interface { SayHi() Sing(song string) BorrowMoney(amount float32)}type ElderlyGent interface { SayHi() Sing(song string) SpendSalary(amount float32)}
通過上面的代碼我們可以知道,interface可以被任意的對象實現。我們看到上面的Men interface被Human、Student和Employee實現。同理,一個對象可以實現任意多個interface,例如上面的Student實現了Men和YoungChap兩個interface。
最後,任意的類型都實現了空interface(我們這樣定義:interface{}),也就是包含0個method的interface。