接口于依赖
Duck Type式接口实现
定义接口
type Programmer interface {
WriteHelloWorld () string
}
接口实现
type GoProgrammer struct{}
func (p *GoProgrammer) WriteHelloWorld() string {
return "Hello World"
}
Go接口
- 接口为非侵入性的,实现不依赖接口定义
- 所以接口的定义可以包含在接口使用者包内
接口变量
自定义类型
type IntConvertionFn func(n int) inttype MyPint int
type myFunc func(int) int
func timeSpent(inner myFunc) myFunc {
return func(n int) int {
start := time.Now()
ret := inner(n)
fmt.Println("time spent : ", time.Since(start).Seconds())
return ret
}
}
func slowFun(op int) int {
time.Sleep(time.Second * 1)
return op
}
func TestMultiValues(t *testing.T) {
tsSF := timeSpent(slowFun)
t.Log(tsSF(10))
}