Go 語言聖經 7.3 實現接口的條件

7.3 實現接口的條件

知識點

  • 1.表達一個類型屬於某個接口只要這個類型實現這個接口
  • 2.即使具體類型有其它的方法也只有接口類型暴露出來的方法會被調用到
  • 3.因爲接口類型被稱爲空接口類型,因此可以將任意值賦給接口類型

代碼

  • 章節中樣例

func test_interface_condition()  {

    os.Stdout.Write([]byte("hello")) // OK: *os.File has Write method
    //os.Stdout.Close()                // OK: *os.File has Close method
    fmt.Println("\n================================")

    var w io.Writer
    w = os.Stdout
    w.Write([]byte("hello")) // OK: io.Writer has Write method
    //w.Close()//w.Close undefined (type io.Writer has no field or method Close)

    fmt.Println("\n================================")

    var any interface{}
    any = true
    any = 12.34
    any = "hello"
    any = map[string]int{"one": 1}
    any = new(bytes.Buffer)
    fmt.Println(any)
    fmt.Println("================================")

    type Artifact interface {
        Title() string
        Creators() []string
        Created() time.Time
    }
    type Text interface {
        Pages() int
        Words() int
        PageSize() int
    }
    type Audio interface {
        Stream() (io.ReadCloser, error)
        RunningTime() time.Duration
        Format() string // e.g., "MP3", "WAV"
    }
    type Video interface {
        Stream() (io.ReadCloser, error)
        RunningTime() time.Duration
        Format() string // e.g., "MP4", "WMV"
        Resolution() (x, y int)
    }

    type Streamer interface {
        Stream() (io.ReadCloser, error)
        RunningTime() time.Duration
        Format() string
    }
}
——不足之處,歡迎補充——

備註

《Go 語言聖經》

  • 學習記錄所使用的GO版本是1.8
  • 學習記錄所使用的編譯器工具爲GoLand
  • 學習記錄所使用的系統環境爲Mac os
  • 學習者有一定的C語言基礎

代碼倉庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章