go 速學 - 13 - Interface

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

目錄

    • interface
      • 概念
      • 定義介面
      • 實現介面
      • 作為參數的介面
      • 介面類型轉換
      • 嵌入介面
      • 空介面
      • nil 介面

摘要

定義介面,實現介面,使用介面,作為參數的介面,if 和 switch 中的介面,類型轉換,嵌入介面,空介面

interface

概念

  • 只要某個類型擁有該介面的所有方法簽名,即算實現該介面,無需顯式聲明實現哪個介面
  • 介面只有方法聲明,無實現,無欄位
  • 當介面儲存的類型和對象都為 nil 時,介面才為 nil
  • 介面調用不會做 receiver 的自動轉換,即指標只能傳指標
  • 空介面可以作為任何類型資料的容器

定義介面

type Usb interface {    getName() string    connect()}

實現介面

只要實現介面的所有方法就算是實現了該介面

type PhoneConnector struct {    name string}//PhoneConnector類型實現 Usb 介面func (pc PhoneConnector) getName() string {    return pc.name}func (pc PhoneConnector) connect() {    fmt.Println(pc.name, "connect")}

使用介面

var pc Usbpc = PhoneConnector{name: "phoneConnector"}pc.connect() //phoneConnector connect

作為參數的介面

只能使用該介面定義的方法

func disconnect(u Usb) {    fmt.Print(u.getName())    fmt.Println(" disconnect")}disconnect(pc) //phoneConnector disconnect

通過 if 進行類型匹配

func disconnect2(u Usb) {    if c, matched := u.(PhoneConnector); matched {        fmt.Print(c.getName())    } else {        fmt.Print("unknown")    }    fmt.Println(" disconnect2")}disconnect2(pc) //phoneConnector disconnect2

通過 switch 進行類型匹配

func test(u Usb) {    switch t := s.(type) {    case PhoneConnector:        fmt.Println("is PhoneConnector", t)    default:        fmt.Println("unkown type", t)    }}test(pc) //is PhoneConnector {phoneConnector}

介面類型轉換

只能向上轉換,調用父介面的方法

var u Usbpc2 := PhoneConnector{name: "pc2"}u = Usb(pc2)u.connect() //pc2 connect

嵌入介面

type Linker interface {    link()}type DynamicLinker interface {    getName() string    Linker}

空介面

由於沒有任何方法,意味著任何類型都實現了此介面

type Empty interface{}

對空介面進行類型匹配

func test(s interface{}) {    switch t := s.(type) {    case PhoneConnector:        fmt.Println("is PhoneConnector", t)    default:        fmt.Println("unkown type", t)    }}

nil 介面

當介面儲存的類型和對象都為nil時,介面才為nil

var e interface{}fmt.Println(e == nil) //truevar p *int = nile = pfmt.Println(e == nil) //false,介面類型為指標
相關文章

聯繫我們

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