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语言基础

代码仓库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值