接口

71 阅读1分钟

接口于依赖

image.png

Duck Type式接口实现

定义接口

type Programmer interface {
    WriteHelloWorld () string
}

接口实现

type GoProgrammer struct{}

func (p *GoProgrammer) WriteHelloWorld() string {
    return "Hello World"
}

Go接口

  1. 接口为非侵入性的,实现不依赖接口定义
  2. 所以接口的定义可以包含在接口使用者包内

接口变量

image.png

自定义类型

  1. type IntConvertionFn func(n int) int
  2. type 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))
}