對Golang interface的理解

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

理解golang的interface主要在於以下兩點:

  • interface是方法的集合
  • interface是一種類型

簡單樣本

package mainimport "fmt"type Animal interface {    Speak() string}type Cat struct{}func (c Cat) Speak() string {    return "cat"}type Dog struct{}func (d Dog) Speak() string {    return "dog"}func Test(params interface{}) {    fmt.Println(params)}func main() {    animals := []Animal{Cat{}, Dog{}}    for _, animal := range animals {        fmt.Println(animal.Speak())    }        Test("string")    Test(123)    Test(true)}

以上代碼中,定義了Animal為介面,而Cat和Dog兩個結構體分別實現了介面中定義的方法。當interface{}作為函數形參時,可以接受不同類型的參數。

指標與interface

如果將上述代碼的:

func (c Cat) Speak() string {    return "cat"}

修改為:

func (c *Cat) Speak() string {    return "cat"}

再次運行原始碼,就會出現以下錯誤:

cannot use Cat literal (type Cat) as type Animal in array or slice literal:Cat does not implement Animal (Speak method has pointer receiver)

這是因為程式認為Cat並未實現Speak()方法, 而是由 *Cat 實現的。這說明結構體在實現介面方法時並不會隱式轉換類型。

interface 數組

interface{} 作為函數形參和 []interface{} 作為形參有很大區別,樣本如下:

package mainimport (    "fmt")func PrintAll(vals []interface{}) {    for _, val := range vals {        fmt.Println(val)    }}func main() {    names := []string{"stanley", "david", "oscar"}    PrintAll(names)}

以上代碼是無法正常啟動並執行,錯誤提示為:

cannot use names (type []string) as type []interface {} in argument to PrintAll

這說明對介面數組賦值前,必須多一個類型轉換操作,正確代碼如下:

package mainimport (    "fmt")func PrintAll(vals []interface{}) {    for _, val := range vals {        fmt.Println(val)    }}func main() {    names := []string{"stanley", "david", "oscar"}    vals := make([]interface{}, len(names))    for i, v := range names {        vals[i] = v    }    PrintAll(vals)}

以上是關於interface使用的基礎內容。

聯繫我們

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