[go学习笔记]十三、Go语言的相关接口

221 阅读1分钟

接口与依赖

Duck Type 式接口实现

//接口定义
type Programmer interface {
  WriteHelloWorld() Code
}

//接口实现
type GoProgrammer struct {

}
func (p *GoPrpgrammer) WriteHelloWorld() Code {
  return "fmt.Println(\"Hello World!\")"
}

示例代码

package interface__test

import "testing"

type Progarmmer interface {
	WriteHelloWorld() string
}

type GoProgarmmer struct {
	
}

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

func TestClient(t *testing.T)  {
	var p Progarmmer
	p = new(GoProgarmmer)
	t.Log(p.WriteHelloWorld())
}

输出

=== RUN   TestClient
--- PASS: TestClient (0.00s)
    interface_test.go:20: fmt.Println("Hello World")
PASS

Process finished with exit code 0

go语言中 接口的实现,不需要像其他语言一样需要显式引用;

Go 接口

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

接口变量

var prog Coder = &GoProgrammer{}

// prog 包含两部分:类型、数据

//类型
type GoProgammer struct {
}
//数据
&GoProgrammer{}   

自定义类型

* type IntConvertionFn func(n int) int
* type MyPoint int

也可以理解成别名的意思

示例代码

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

// 原函数
// func timeSpent(inner func(op int) int) func(op int)int  {
// 使用别名后的函数,减短了许多,而且更易读了
func timeSpent(inner func(op int) int) 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))
}

输出

=== RUN   TestFn
time spent: 1.004288176
--- PASS: TestFn (1.00s)
    customer_type_test.go:27: 10
PASS

Process finished with exit code 0

示例代码请访问: github.com/wenjianzhan…