面向接口

duck typing 大黄鸭是不是个鸭子?

  • 描述事物外部行为而非内部结构
  • 从使用者的角度来看
  • go 属于结构化类型系统

go lang duck typing

  • 同时具有 python、c++ 的 duck typing 的灵活性(什么类型都可以传)
  • 又具有 java 的类型检查
接口的定义与实现

使用者 ——> 实现者

  • 接口由使用者定义
  • 接口的实现是隐式

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // (使用者定义接口)
    type Retriever interface {
    Get(url string) string
    }
    // 使用者
    func download(r Retriever) string{
    return r.Get("http://www.imooc.com")
    }
    =====
    // 实现者
    type Retriever struct {
    UserAgent string
    TimeOut time.Duration
    }
    // 实现了接口
    func (r Retriever) Get(url string) string {
    return string("result")
    }
接口的值类型
  • 接口变量:实现者的类型、实现者的指针(指向实现者)
  • 接口变量自带指针
  • 接口变量同样采用值传递,几乎不需要使用接口的指针
  • 指针接收者实现只能以指针方式使用,值接收者都可以

  • 查看接口变量

  • 表示任何类型:interface{}
  • Type Assertion
  • Type Switch
接口的组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// (使用者定义接口1)
type Retriever interface {
Get(url string) string
}
//(使用者定义接口2)
type Poster interface {
Post(url string,
form map[string]string) string
}
// 组合接口(1 + 2)
type RetrieverPoster interface {
Retriever
Poster
}
//使用组合接口
func seesion(s RetrieverPoster) {
s.Get()
s.Post()
}
接口的值类型
  • 接口变量:实现者的类型、实现者的指针(指向实现者)
  • 接口变量自带指针
  • 接口变量同样采用值传递,几乎不需要使用接口的指针
  • 指针接收者实现只能以指针方式使用,值接收者都可以

  • 查看接口变量

  • 表示任何类型:interface{}
  • Type Assertion
  • Type Switch
接口的组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// (使用者定义接口1)
type Retriever interface {
Get(url string) string
}
//(使用者定义接口2)
type Poster interface {
Post(url string,
form map[string]string) string
}
// 组合接口(1 + 2)
type RetrieverPoster interface {
Retriever
Poster
}
//使用组合接口
func seesion(s RetrieverPoster) {
s.Get()
s.Post()
}
常用系统接口
  • Stringer
  • Reader
  • Writer