16丨Go语言的相关接口

定义交互协议

 接口与依赖

 客户端与接口之间存在循环依赖的问题

 

Duck Type 式接口实现

Go 接口

与其他主要编程语⾔的差异
1. 接口为⾮⼊侵性,实现不依赖于借⼝定义
2. 所以接⼝的定义可以包含在接口使⽤者包内

接口变量

自定义类型

1. type IntConvertionFn func(n int) int
2. type MyPoint int

测试代码

接口

package interface_test

import "testing"

type Programmer interface {
    WriteHelloWorld() string
}

type GoProgrammer struct {
}

func (g *GoProgrammer) WriteHelloWorld() string {
    return "fmt.Println(\"Hello World\")"
}

func TestClient(t *testing.T) {
    var p Programmer
    p = new(GoProgrammer)
    t.Log(p.WriteHelloWorld()) //fmt.Println("Hello World")
}

自定义类型

package customer_type

import (
    "fmt"
    "testing"
    "time"
)

// 自定义类型
type IntConv func(op int) int

//    名称    类型        返回值

// 装饰器函数    形参   类型       反回值
func timeSpent(inner IntConv) IntConv {
    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 TestFn(t *testing.T) {
    tsSF := timeSpent(slowFun)
    t.Log(tsSF(10))
}

 

posted @ 2021-01-23 10:11  元贞  阅读(44)  评论(0)    收藏  举报